Merge commit 'refs/top-bases/t/blame/extra-columns' into t/blame/extra-columns
[git/gitweb.git] / gitweb / gitweb.perl
blob2d5845a576bbcb6f4c9fd15ace5818440576b3bf
1 #!/usr/bin/perl
3 # gitweb - simple web interface to track changes in git repositories
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
8 # This program is licensed under the GPLv2
10 use strict;
11 use warnings;
12 use CGI qw(:standard :escapeHTML -nosticky);
13 use CGI::Util qw(unescape);
14 use CGI::Carp qw(fatalsToBrowser);
15 use Encode;
16 use Fcntl ':mode';
17 use File::Find qw();
18 use File::Basename qw(basename);
19 binmode STDOUT, ':utf8';
21 BEGIN {
22 CGI->compile() if $ENV{'MOD_PERL'};
25 our $cgi = new CGI;
26 our $version = "++GIT_VERSION++";
27 our $my_url = $cgi->url();
28 our $my_uri = $cgi->url(-absolute => 1);
30 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
31 # needed and used only for URLs with nonempty PATH_INFO
32 our $base_url = $my_url;
34 # When the script is used as DirectoryIndex, the URL does not contain the name
35 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
36 # have to do it ourselves. We make $path_info global because it's also used
37 # later on.
39 # Another issue with the script being the DirectoryIndex is that the resulting
40 # $my_url data is not the full script URL: this is good, because we want
41 # generated links to keep implying the script name if it wasn't explicitly
42 # indicated in the URL we're handling, but it means that $my_url cannot be used
43 # as base URL.
44 # Therefore, if we needed to strip PATH_INFO, then we know that we have
45 # to build the base URL ourselves:
46 our $path_info = $ENV{"PATH_INFO"};
47 if ($path_info) {
48 if ($my_url =~ s,\Q$path_info\E$,, &&
49 $my_uri =~ s,\Q$path_info\E$,, &&
50 defined $ENV{'SCRIPT_NAME'}) {
51 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
55 # core git executable to use
56 # this can just be "git" if your webserver has a sensible PATH
57 our $GIT = "++GIT_BINDIR++/git";
59 # absolute fs-path which will be prepended to the project path
60 #our $projectroot = "/pub/scm";
61 our $projectroot = "++GITWEB_PROJECTROOT++";
63 # fs traversing limit for getting project list
64 # the number is relative to the projectroot
65 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
67 # target of the home link on top of all pages
68 our $home_link = $my_uri || "/";
70 # string of the home link on top of all pages
71 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
73 # name of your site or organization to appear in page titles
74 # replace this with something more descriptive for clearer bookmarks
75 our $site_name = "++GITWEB_SITENAME++"
76 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
78 # filename of html text to include at top of each page
79 our $site_header = "++GITWEB_SITE_HEADER++";
80 # html text to include at home page
81 our $home_text = "++GITWEB_HOMETEXT++";
82 # filename of html text to include at bottom of each page
83 our $site_footer = "++GITWEB_SITE_FOOTER++";
85 # URI of stylesheets
86 our @stylesheets = ("++GITWEB_CSS++");
87 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
88 our $stylesheet = undef;
89 # URI of GIT logo (72x27 size)
90 our $logo = "++GITWEB_LOGO++";
91 # URI of GIT favicon, assumed to be image/png type
92 our $favicon = "++GITWEB_FAVICON++";
93 # URI of gitweb.js
94 our $gitwebjs = "++GITWEB_GITWEBJS++";
96 # URI and label (title) of GIT logo link
97 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
98 #our $logo_label = "git documentation";
99 our $logo_url = "http://git-scm.com/";
100 our $logo_label = "git homepage";
102 # source of projects list
103 our $projects_list = "++GITWEB_LIST++";
105 # the width (in characters) of the projects list "Description" column
106 our $projects_list_description_width = 25;
108 # default order of projects list
109 # valid values are none, project, descr, owner, and age
110 our $default_projects_order = "project";
112 # show repository only if this file exists
113 # (only effective if this variable evaluates to true)
114 our $export_ok = "++GITWEB_EXPORT_OK++";
116 # show repository only if this subroutine returns true
117 # when given the path to the project, for example:
118 # sub { return -e "$_[0]/git-daemon-export-ok"; }
119 our $export_auth_hook = undef;
121 # only allow viewing of repositories also shown on the overview page
122 our $strict_export = "++GITWEB_STRICT_EXPORT++";
124 # list of git base URLs used for URL to where fetch project from,
125 # i.e. full URL is "$git_base_url/$project"
126 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
128 # default blob_plain mimetype and default charset for text/plain blob
129 our $default_blob_plain_mimetype = 'text/plain';
130 our $default_text_plain_charset = undef;
132 # file to use for guessing MIME types before trying /etc/mime.types
133 # (relative to the current git repository)
134 our $mimetypes_file = undef;
136 # assume this charset if line contains non-UTF-8 characters;
137 # it should be valid encoding (see Encoding::Supported(3pm) for list),
138 # for which encoding all byte sequences are valid, for example
139 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
140 # could be even 'utf-8' for the old behavior)
141 our $fallback_encoding = 'latin1';
143 # rename detection options for git-diff and git-diff-tree
144 # - default is '-M', with the cost proportional to
145 # (number of removed files) * (number of new files).
146 # - more costly is '-C' (which implies '-M'), with the cost proportional to
147 # (number of changed files + number of removed files) * (number of new files)
148 # - even more costly is '-C', '--find-copies-harder' with cost
149 # (number of files in the original tree) * (number of new files)
150 # - one might want to include '-B' option, e.g. '-B', '-M'
151 our @diff_opts = ('-M'); # taken from git_commit
153 # Disables features that would allow repository owners to inject script into
154 # the gitweb domain.
155 our $prevent_xss = 0;
157 # information about snapshot formats that gitweb is capable of serving
158 our %known_snapshot_formats = (
159 # name => {
160 # 'display' => display name,
161 # 'type' => mime type,
162 # 'suffix' => filename suffix,
163 # 'format' => --format for git-archive,
164 # 'compressor' => [compressor command and arguments]
165 # (array reference, optional)
166 # 'disabled' => boolean (optional)}
168 'tgz' => {
169 'display' => 'tar.gz',
170 'type' => 'application/x-gzip',
171 'suffix' => '.tar.gz',
172 'format' => 'tar',
173 'compressor' => ['gzip']},
175 'tbz2' => {
176 'display' => 'tar.bz2',
177 'type' => 'application/x-bzip2',
178 'suffix' => '.tar.bz2',
179 'format' => 'tar',
180 'compressor' => ['bzip2']},
182 'txz' => {
183 'display' => 'tar.xz',
184 'type' => 'application/x-xz',
185 'suffix' => '.tar.xz',
186 'format' => 'tar',
187 'compressor' => ['xz'],
188 'disabled' => 1},
190 'zip' => {
191 'display' => 'zip',
192 'type' => 'application/x-zip',
193 'suffix' => '.zip',
194 'format' => 'zip'},
197 # Aliases so we understand old gitweb.snapshot values in repository
198 # configuration.
199 our %known_snapshot_format_aliases = (
200 'gzip' => 'tgz',
201 'bzip2' => 'tbz2',
202 'xz' => 'txz',
204 # backward compatibility: legacy gitweb config support
205 'x-gzip' => undef, 'gz' => undef,
206 'x-bzip2' => undef, 'bz2' => undef,
207 'x-zip' => undef, '' => undef,
210 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
211 # are changed, it may be appropriate to change these values too via
212 # $GITWEB_CONFIG.
213 our %avatar_size = (
214 'default' => 16,
215 'double' => 32
218 # You define site-wide feature defaults here; override them with
219 # $GITWEB_CONFIG as necessary.
220 our %feature = (
221 # feature => {
222 # 'sub' => feature-sub (subroutine),
223 # 'override' => allow-override (boolean),
224 # 'default' => [ default options...] (array reference)}
226 # if feature is overridable (it means that allow-override has true value),
227 # then feature-sub will be called with default options as parameters;
228 # return value of feature-sub indicates if to enable specified feature
230 # if there is no 'sub' key (no feature-sub), then feature cannot be
231 # overriden
233 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
234 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
235 # is enabled
237 # Enable the 'blame' blob view, showing the last commit that modified
238 # each line in the file. This can be very CPU-intensive.
240 # To enable system wide have in $GITWEB_CONFIG
241 # $feature{'blame'}{'default'} = [1];
242 # To have project specific config enable override in $GITWEB_CONFIG
243 # $feature{'blame'}{'override'} = 1;
244 # and in project config gitweb.blame = 0|1;
245 'blame' => {
246 'sub' => sub { feature_bool('blame', @_) },
247 'override' => 0,
248 'default' => [0]},
250 # Enable the 'incremental blame' blob view, which uses javascript to
251 # incrementally show the revisions of lines as they are discovered
252 # in the history. It is better for large histories, files and slow
253 # servers, but requires javascript in the client, can slow down the
254 # browser on large files and does not show author initials.
256 # To enable system wide have in $GITWEB_CONFIG
257 # $feature{'blame_incremental'}{'default'} = [1];
258 # To have project specific config enable override in $GITWEB_CONFIG
259 # $feature{'blame_incremental'}{'override'} = 1;
260 # and in project config gitweb.blame_incremental = 0|1;
261 'blame_incremental' => {
262 'sub' => sub { feature_bool('blame_incremental', @_) },
263 'override' => 0,
264 'default' => [0]},
266 # Enable the 'snapshot' link, providing a compressed archive of any
267 # tree. This can potentially generate high traffic if you have large
268 # project.
270 # Value is a list of formats defined in %known_snapshot_formats that
271 # you wish to offer.
272 # To disable system wide have in $GITWEB_CONFIG
273 # $feature{'snapshot'}{'default'} = [];
274 # To have project specific config enable override in $GITWEB_CONFIG
275 # $feature{'snapshot'}{'override'} = 1;
276 # and in project config, a comma-separated list of formats or "none"
277 # to disable. Example: gitweb.snapshot = tbz2,zip;
278 'snapshot' => {
279 'sub' => \&feature_snapshot,
280 'override' => 0,
281 'default' => ['tgz']},
283 # Enable text search, which will list the commits which match author,
284 # committer or commit text to a given string. Enabled by default.
285 # Project specific override is not supported.
286 'search' => {
287 'override' => 0,
288 'default' => [1]},
290 # Enable grep search, which will list the files in currently selected
291 # tree containing the given string. Enabled by default. This can be
292 # potentially CPU-intensive, of course.
294 # To enable system wide have in $GITWEB_CONFIG
295 # $feature{'grep'}{'default'} = [1];
296 # To have project specific config enable override in $GITWEB_CONFIG
297 # $feature{'grep'}{'override'} = 1;
298 # and in project config gitweb.grep = 0|1;
299 'grep' => {
300 'sub' => sub { feature_bool('grep', @_) },
301 'override' => 0,
302 'default' => [1]},
304 # Enable the pickaxe search, which will list the commits that modified
305 # a given string in a file. This can be practical and quite faster
306 # alternative to 'blame', but still potentially CPU-intensive.
308 # To enable system wide have in $GITWEB_CONFIG
309 # $feature{'pickaxe'}{'default'} = [1];
310 # To have project specific config enable override in $GITWEB_CONFIG
311 # $feature{'pickaxe'}{'override'} = 1;
312 # and in project config gitweb.pickaxe = 0|1;
313 'pickaxe' => {
314 'sub' => sub { feature_bool('pickaxe', @_) },
315 'override' => 0,
316 'default' => [1]},
318 # Enable showing size of blobs in a 'tree' view, in a separate
319 # column, similar to what 'ls -l' does. This cost a bit of IO.
321 # To disable system wide have in $GITWEB_CONFIG
322 # $feature{'show-sizes'}{'default'} = [0];
323 # To have project specific config enable override in $GITWEB_CONFIG
324 # $feature{'show-sizes'}{'override'} = 1;
325 # and in project config gitweb.showsizes = 0|1;
326 'show-sizes' => {
327 'sub' => sub { feature_bool('showsizes', @_) },
328 'override' => 0,
329 'default' => [1]},
331 # Make gitweb use an alternative format of the URLs which can be
332 # more readable and natural-looking: project name is embedded
333 # directly in the path and the query string contains other
334 # auxiliary information. All gitweb installations recognize
335 # URL in either format; this configures in which formats gitweb
336 # generates links.
338 # To enable system wide have in $GITWEB_CONFIG
339 # $feature{'pathinfo'}{'default'} = [1];
340 # Project specific override is not supported.
342 # Note that you will need to change the default location of CSS,
343 # favicon, logo and possibly other files to an absolute URL. Also,
344 # if gitweb.cgi serves as your indexfile, you will need to force
345 # $my_uri to contain the script name in your $GITWEB_CONFIG.
346 'pathinfo' => {
347 'override' => 0,
348 'default' => [0]},
350 # Make gitweb consider projects in project root subdirectories
351 # to be forks of existing projects. Given project $projname.git,
352 # projects matching $projname/*.git will not be shown in the main
353 # projects list, instead a '+' mark will be added to $projname
354 # there and a 'forks' view will be enabled for the project, listing
355 # all the forks. If project list is taken from a file, forks have
356 # to be listed after the main project.
358 # To enable system wide have in $GITWEB_CONFIG
359 # $feature{'forks'}{'default'} = [1];
360 # Project specific override is not supported.
361 'forks' => {
362 'override' => 0,
363 'default' => [0]},
365 # Insert custom links to the action bar of all project pages.
366 # This enables you mainly to link to third-party scripts integrating
367 # into gitweb; e.g. git-browser for graphical history representation
368 # or custom web-based repository administration interface.
370 # The 'default' value consists of a list of triplets in the form
371 # (label, link, position) where position is the label after which
372 # to insert the link and link is a format string where %n expands
373 # to the project name, %f to the project path within the filesystem,
374 # %h to the current hash (h gitweb parameter) and %b to the current
375 # hash base (hb gitweb parameter); %% expands to %.
377 # To enable system wide have in $GITWEB_CONFIG e.g.
378 # $feature{'actions'}{'default'} = [('graphiclog',
379 # '/git-browser/by-commit.html?r=%n', 'summary')];
380 # Project specific override is not supported.
381 'actions' => {
382 'override' => 0,
383 'default' => []},
385 # Allow gitweb scan project content tags described in ctags/
386 # of project repository, and display the popular Web 2.0-ish
387 # "tag cloud" near the project list. Note that this is something
388 # COMPLETELY different from the normal Git tags.
390 # gitweb by itself can show existing tags, but it does not handle
391 # tagging itself; you need an external application for that.
392 # For an example script, check Girocco's cgi/tagproj.cgi.
393 # You may want to install the HTML::TagCloud Perl module to get
394 # a pretty tag cloud instead of just a list of tags.
396 # To enable system wide have in $GITWEB_CONFIG
397 # $feature{'ctags'}{'default'} = ['path_to_tag_script'];
398 # Project specific override is not supported.
399 'ctags' => {
400 'override' => 0,
401 'default' => [0]},
403 # The maximum number of patches in a patchset generated in patch
404 # view. Set this to 0 or undef to disable patch view, or to a
405 # negative number to remove any limit.
407 # To disable system wide have in $GITWEB_CONFIG
408 # $feature{'patches'}{'default'} = [0];
409 # To have project specific config enable override in $GITWEB_CONFIG
410 # $feature{'patches'}{'override'} = 1;
411 # and in project config gitweb.patches = 0|n;
412 # where n is the maximum number of patches allowed in a patchset.
413 'patches' => {
414 'sub' => \&feature_patches,
415 'override' => 0,
416 'default' => [16]},
418 # Avatar support. When this feature is enabled, views such as
419 # shortlog or commit will display an avatar associated with
420 # the email of the committer(s) and/or author(s).
422 # Currently available providers are gravatar and picon.
423 # If an unknown provider is specified, the feature is disabled.
425 # Gravatar depends on Digest::MD5.
426 # Picon currently relies on the indiana.edu database.
428 # To enable system wide have in $GITWEB_CONFIG
429 # $feature{'avatar'}{'default'} = ['<provider>'];
430 # where <provider> is either gravatar or picon.
431 # To have project specific config enable override in $GITWEB_CONFIG
432 # $feature{'avatar'}{'override'} = 1;
433 # and in project config gitweb.avatar = <provider>;
434 'avatar' => {
435 'sub' => \&feature_avatar,
436 'override' => 0,
437 'default' => ['']},
440 sub gitweb_get_feature {
441 my ($name) = @_;
442 return unless exists $feature{$name};
443 my ($sub, $override, @defaults) = (
444 $feature{$name}{'sub'},
445 $feature{$name}{'override'},
446 @{$feature{$name}{'default'}});
447 if (!$override) { return @defaults; }
448 if (!defined $sub) {
449 warn "feature $name is not overridable";
450 return @defaults;
452 return $sub->(@defaults);
455 # A wrapper to check if a given feature is enabled.
456 # With this, you can say
458 # my $bool_feat = gitweb_check_feature('bool_feat');
459 # gitweb_check_feature('bool_feat') or somecode;
461 # instead of
463 # my ($bool_feat) = gitweb_get_feature('bool_feat');
464 # (gitweb_get_feature('bool_feat'))[0] or somecode;
466 sub gitweb_check_feature {
467 return (gitweb_get_feature(@_))[0];
471 sub feature_bool {
472 my $key = shift;
473 my ($val) = git_get_project_config($key, '--bool');
475 if (!defined $val) {
476 return ($_[0]);
477 } elsif ($val eq 'true') {
478 return (1);
479 } elsif ($val eq 'false') {
480 return (0);
484 sub feature_snapshot {
485 my (@fmts) = @_;
487 my ($val) = git_get_project_config('snapshot');
489 if ($val) {
490 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
493 return @fmts;
496 sub feature_patches {
497 my @val = (git_get_project_config('patches', '--int'));
499 if (@val) {
500 return @val;
503 return ($_[0]);
506 sub feature_avatar {
507 my @val = (git_get_project_config('avatar'));
509 return @val ? @val : @_;
512 # checking HEAD file with -e is fragile if the repository was
513 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
514 # and then pruned.
515 sub check_head_link {
516 my ($dir) = @_;
517 my $headfile = "$dir/HEAD";
518 return ((-e $headfile) ||
519 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
522 sub check_export_ok {
523 my ($dir) = @_;
524 return (check_head_link($dir) &&
525 (!$export_ok || -e "$dir/$export_ok") &&
526 (!$export_auth_hook || $export_auth_hook->($dir)));
529 # process alternate names for backward compatibility
530 # filter out unsupported (unknown) snapshot formats
531 sub filter_snapshot_fmts {
532 my @fmts = @_;
534 @fmts = map {
535 exists $known_snapshot_format_aliases{$_} ?
536 $known_snapshot_format_aliases{$_} : $_} @fmts;
537 @fmts = grep {
538 exists $known_snapshot_formats{$_} &&
539 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
542 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
543 if (-e $GITWEB_CONFIG) {
544 do $GITWEB_CONFIG;
545 } else {
546 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
547 do $GITWEB_CONFIG_SYSTEM if -e $GITWEB_CONFIG_SYSTEM;
550 # version of the core git binary
551 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
553 $projects_list ||= $projectroot;
555 # ======================================================================
556 # input validation and dispatch
558 # input parameters can be collected from a variety of sources (presently, CGI
559 # and PATH_INFO), so we define an %input_params hash that collects them all
560 # together during validation: this allows subsequent uses (e.g. href()) to be
561 # agnostic of the parameter origin
563 our %input_params = ();
565 # input parameters are stored with the long parameter name as key. This will
566 # also be used in the href subroutine to convert parameters to their CGI
567 # equivalent, and since the href() usage is the most frequent one, we store
568 # the name -> CGI key mapping here, instead of the reverse.
570 # XXX: Warning: If you touch this, check the search form for updating,
571 # too.
573 our @cgi_param_mapping = (
574 project => "p",
575 action => "a",
576 file_name => "f",
577 file_parent => "fp",
578 hash => "h",
579 hash_parent => "hp",
580 hash_base => "hb",
581 hash_parent_base => "hpb",
582 page => "pg",
583 order => "o",
584 searchtext => "s",
585 searchtype => "st",
586 snapshot_format => "sf",
587 extra_options => "opt",
588 search_use_regexp => "sr",
590 our %cgi_param_mapping = @cgi_param_mapping;
592 # we will also need to know the possible actions, for validation
593 our %actions = (
594 "blame" => \&git_blame,
595 "blame_incremental" => \&git_blame_incremental,
596 "blame_data" => \&git_blame_data,
597 "blobdiff" => \&git_blobdiff,
598 "blobdiff_plain" => \&git_blobdiff_plain,
599 "blob" => \&git_blob,
600 "blob_plain" => \&git_blob_plain,
601 "commitdiff" => \&git_commitdiff,
602 "commitdiff_plain" => \&git_commitdiff_plain,
603 "commit" => \&git_commit,
604 "forks" => \&git_forks,
605 "heads" => \&git_heads,
606 "history" => \&git_history,
607 "log" => \&git_log,
608 "patch" => \&git_patch,
609 "patches" => \&git_patches,
610 "rss" => \&git_rss,
611 "atom" => \&git_atom,
612 "search" => \&git_search,
613 "search_help" => \&git_search_help,
614 "shortlog" => \&git_shortlog,
615 "summary" => \&git_summary,
616 "tag" => \&git_tag,
617 "tags" => \&git_tags,
618 "tree" => \&git_tree,
619 "snapshot" => \&git_snapshot,
620 "object" => \&git_object,
621 # those below don't need $project
622 "opml" => \&git_opml,
623 "project_list" => \&git_project_list,
624 "project_index" => \&git_project_index,
627 # finally, we have the hash of allowed extra_options for the commands that
628 # allow them
629 our %allowed_options = (
630 "--no-merges" => [ qw(rss atom log shortlog history) ],
633 # fill %input_params with the CGI parameters. All values except for 'opt'
634 # should be single values, but opt can be an array. We should probably
635 # build an array of parameters that can be multi-valued, but since for the time
636 # being it's only this one, we just single it out
637 while (my ($name, $symbol) = each %cgi_param_mapping) {
638 if ($symbol eq 'opt') {
639 $input_params{$name} = [ $cgi->param($symbol) ];
640 } else {
641 $input_params{$name} = $cgi->param($symbol);
645 # now read PATH_INFO and update the parameter list for missing parameters
646 sub evaluate_path_info {
647 return if defined $input_params{'project'};
648 return if !$path_info;
649 $path_info =~ s,^/+,,;
650 return if !$path_info;
652 # find which part of PATH_INFO is project
653 my $project = $path_info;
654 $project =~ s,/+$,,;
655 while ($project && !check_head_link("$projectroot/$project")) {
656 $project =~ s,/*[^/]*$,,;
658 return unless $project;
659 $input_params{'project'} = $project;
661 # do not change any parameters if an action is given using the query string
662 return if $input_params{'action'};
663 $path_info =~ s,^\Q$project\E/*,,;
665 # next, check if we have an action
666 my $action = $path_info;
667 $action =~ s,/.*$,,;
668 if (exists $actions{$action}) {
669 $path_info =~ s,^$action/*,,;
670 $input_params{'action'} = $action;
673 # list of actions that want hash_base instead of hash, but can have no
674 # pathname (f) parameter
675 my @wants_base = (
676 'tree',
677 'history',
680 # we want to catch
681 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
682 my ($parentrefname, $parentpathname, $refname, $pathname) =
683 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?(.+?)(?::(.+))?$/);
685 # first, analyze the 'current' part
686 if (defined $pathname) {
687 # we got "branch:filename" or "branch:dir/"
688 # we could use git_get_type(branch:pathname), but:
689 # - it needs $git_dir
690 # - it does a git() call
691 # - the convention of terminating directories with a slash
692 # makes it superfluous
693 # - embedding the action in the PATH_INFO would make it even
694 # more superfluous
695 $pathname =~ s,^/+,,;
696 if (!$pathname || substr($pathname, -1) eq "/") {
697 $input_params{'action'} ||= "tree";
698 $pathname =~ s,/$,,;
699 } else {
700 # the default action depends on whether we had parent info
701 # or not
702 if ($parentrefname) {
703 $input_params{'action'} ||= "blobdiff_plain";
704 } else {
705 $input_params{'action'} ||= "blob_plain";
708 $input_params{'hash_base'} ||= $refname;
709 $input_params{'file_name'} ||= $pathname;
710 } elsif (defined $refname) {
711 # we got "branch". In this case we have to choose if we have to
712 # set hash or hash_base.
714 # Most of the actions without a pathname only want hash to be
715 # set, except for the ones specified in @wants_base that want
716 # hash_base instead. It should also be noted that hand-crafted
717 # links having 'history' as an action and no pathname or hash
718 # set will fail, but that happens regardless of PATH_INFO.
719 $input_params{'action'} ||= "shortlog";
720 if (grep { $_ eq $input_params{'action'} } @wants_base) {
721 $input_params{'hash_base'} ||= $refname;
722 } else {
723 $input_params{'hash'} ||= $refname;
727 # next, handle the 'parent' part, if present
728 if (defined $parentrefname) {
729 # a missing pathspec defaults to the 'current' filename, allowing e.g.
730 # someproject/blobdiff/oldrev..newrev:/filename
731 if ($parentpathname) {
732 $parentpathname =~ s,^/+,,;
733 $parentpathname =~ s,/$,,;
734 $input_params{'file_parent'} ||= $parentpathname;
735 } else {
736 $input_params{'file_parent'} ||= $input_params{'file_name'};
738 # we assume that hash_parent_base is wanted if a path was specified,
739 # or if the action wants hash_base instead of hash
740 if (defined $input_params{'file_parent'} ||
741 grep { $_ eq $input_params{'action'} } @wants_base) {
742 $input_params{'hash_parent_base'} ||= $parentrefname;
743 } else {
744 $input_params{'hash_parent'} ||= $parentrefname;
748 # for the snapshot action, we allow URLs in the form
749 # $project/snapshot/$hash.ext
750 # where .ext determines the snapshot and gets removed from the
751 # passed $refname to provide the $hash.
753 # To be able to tell that $refname includes the format extension, we
754 # require the following two conditions to be satisfied:
755 # - the hash input parameter MUST have been set from the $refname part
756 # of the URL (i.e. they must be equal)
757 # - the snapshot format MUST NOT have been defined already (e.g. from
758 # CGI parameter sf)
759 # It's also useless to try any matching unless $refname has a dot,
760 # so we check for that too
761 if (defined $input_params{'action'} &&
762 $input_params{'action'} eq 'snapshot' &&
763 defined $refname && index($refname, '.') != -1 &&
764 $refname eq $input_params{'hash'} &&
765 !defined $input_params{'snapshot_format'}) {
766 # We loop over the known snapshot formats, checking for
767 # extensions. Allowed extensions are both the defined suffix
768 # (which includes the initial dot already) and the snapshot
769 # format key itself, with a prepended dot
770 while (my ($fmt, $opt) = each %known_snapshot_formats) {
771 my $hash = $refname;
772 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
773 next;
775 my $sfx = $1;
776 # a valid suffix was found, so set the snapshot format
777 # and reset the hash parameter
778 $input_params{'snapshot_format'} = $fmt;
779 $input_params{'hash'} = $hash;
780 # we also set the format suffix to the one requested
781 # in the URL: this way a request for e.g. .tgz returns
782 # a .tgz instead of a .tar.gz
783 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
784 last;
788 evaluate_path_info();
790 our $action = $input_params{'action'};
791 if (defined $action) {
792 if (!validate_action($action)) {
793 die_error(400, "Invalid action parameter");
797 # parameters which are pathnames
798 our $project = $input_params{'project'};
799 if (defined $project) {
800 if (!validate_project($project)) {
801 undef $project;
802 die_error(404, "No such project");
806 our $file_name = $input_params{'file_name'};
807 if (defined $file_name) {
808 if (!validate_pathname($file_name)) {
809 die_error(400, "Invalid file parameter");
813 our $file_parent = $input_params{'file_parent'};
814 if (defined $file_parent) {
815 if (!validate_pathname($file_parent)) {
816 die_error(400, "Invalid file parent parameter");
820 # parameters which are refnames
821 our $hash = $input_params{'hash'};
822 if (defined $hash) {
823 if (!validate_refname($hash)) {
824 die_error(400, "Invalid hash parameter");
828 our $hash_parent = $input_params{'hash_parent'};
829 if (defined $hash_parent) {
830 if (!validate_refname($hash_parent)) {
831 die_error(400, "Invalid hash parent parameter");
835 our $hash_base = $input_params{'hash_base'};
836 if (defined $hash_base) {
837 if (!validate_refname($hash_base)) {
838 die_error(400, "Invalid hash base parameter");
842 our @extra_options = @{$input_params{'extra_options'}};
843 # @extra_options is always defined, since it can only be (currently) set from
844 # CGI, and $cgi->param() returns the empty array in array context if the param
845 # is not set
846 foreach my $opt (@extra_options) {
847 if (not exists $allowed_options{$opt}) {
848 die_error(400, "Invalid option parameter");
850 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
851 die_error(400, "Invalid option parameter for this action");
855 our $hash_parent_base = $input_params{'hash_parent_base'};
856 if (defined $hash_parent_base) {
857 if (!validate_refname($hash_parent_base)) {
858 die_error(400, "Invalid hash parent base parameter");
862 # other parameters
863 our $page = $input_params{'page'};
864 if (defined $page) {
865 if ($page =~ m/[^0-9]/) {
866 die_error(400, "Invalid page parameter");
870 our $searchtype = $input_params{'searchtype'};
871 if (defined $searchtype) {
872 if ($searchtype =~ m/[^a-z]/) {
873 die_error(400, "Invalid searchtype parameter");
877 our $search_use_regexp = $input_params{'search_use_regexp'};
879 our $searchtext = $input_params{'searchtext'};
880 our $search_regexp;
881 if (defined $searchtext) {
882 if (length($searchtext) < 2) {
883 die_error(403, "At least two characters are required for search parameter");
885 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
888 # path to the current git repository
889 our $git_dir;
890 $git_dir = "$projectroot/$project" if $project;
892 # list of supported snapshot formats
893 our @snapshot_fmts = gitweb_get_feature('snapshot');
894 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
896 # check that the avatar feature is set to a known provider name,
897 # and for each provider check if the dependencies are satisfied.
898 # if the provider name is invalid or the dependencies are not met,
899 # reset $git_avatar to the empty string.
900 our ($git_avatar) = gitweb_get_feature('avatar');
901 if ($git_avatar eq 'gravatar') {
902 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
903 } elsif ($git_avatar eq 'picon') {
904 # no dependencies
905 } else {
906 $git_avatar = '';
909 # dispatch
910 if (!defined $action) {
911 if (defined $hash) {
912 $action = git_get_type($hash);
913 } elsif (defined $hash_base && defined $file_name) {
914 $action = git_get_type("$hash_base:$file_name");
915 } elsif (defined $project) {
916 $action = 'summary';
917 } else {
918 $action = 'project_list';
921 if (!defined($actions{$action})) {
922 die_error(400, "Unknown action");
924 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
925 !$project) {
926 die_error(400, "Project needed");
928 $actions{$action}->();
929 exit;
931 ## ======================================================================
932 ## action links
934 sub href {
935 my %params = @_;
936 # default is to use -absolute url() i.e. $my_uri
937 my $href = $params{-full} ? $my_url : $my_uri;
939 $params{'project'} = $project unless exists $params{'project'};
941 if ($params{-replay}) {
942 while (my ($name, $symbol) = each %cgi_param_mapping) {
943 if (!exists $params{$name}) {
944 $params{$name} = $input_params{$name};
949 my $use_pathinfo = gitweb_check_feature('pathinfo');
950 if ($use_pathinfo and defined $params{'project'}) {
951 # try to put as many parameters as possible in PATH_INFO:
952 # - project name
953 # - action
954 # - hash_parent or hash_parent_base:/file_parent
955 # - hash or hash_base:/filename
956 # - the snapshot_format as an appropriate suffix
958 # When the script is the root DirectoryIndex for the domain,
959 # $href here would be something like http://gitweb.example.com/
960 # Thus, we strip any trailing / from $href, to spare us double
961 # slashes in the final URL
962 $href =~ s,/$,,;
964 # Then add the project name, if present
965 $href .= "/".esc_url($params{'project'});
966 delete $params{'project'};
968 # since we destructively absorb parameters, we keep this
969 # boolean that remembers if we're handling a snapshot
970 my $is_snapshot = $params{'action'} eq 'snapshot';
972 # Summary just uses the project path URL, any other action is
973 # added to the URL
974 if (defined $params{'action'}) {
975 $href .= "/".esc_url($params{'action'}) unless $params{'action'} eq 'summary';
976 delete $params{'action'};
979 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
980 # stripping nonexistent or useless pieces
981 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
982 || $params{'hash_parent'} || $params{'hash'});
983 if (defined $params{'hash_base'}) {
984 if (defined $params{'hash_parent_base'}) {
985 $href .= esc_url($params{'hash_parent_base'});
986 # skip the file_parent if it's the same as the file_name
987 if (defined $params{'file_parent'}) {
988 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
989 delete $params{'file_parent'};
990 } elsif ($params{'file_parent'} !~ /\.\./) {
991 $href .= ":/".esc_url($params{'file_parent'});
992 delete $params{'file_parent'};
995 $href .= "..";
996 delete $params{'hash_parent'};
997 delete $params{'hash_parent_base'};
998 } elsif (defined $params{'hash_parent'}) {
999 $href .= esc_url($params{'hash_parent'}). "..";
1000 delete $params{'hash_parent'};
1003 $href .= esc_url($params{'hash_base'});
1004 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1005 $href .= ":/".esc_url($params{'file_name'});
1006 delete $params{'file_name'};
1008 delete $params{'hash'};
1009 delete $params{'hash_base'};
1010 } elsif (defined $params{'hash'}) {
1011 $href .= esc_url($params{'hash'});
1012 delete $params{'hash'};
1015 # If the action was a snapshot, we can absorb the
1016 # snapshot_format parameter too
1017 if ($is_snapshot) {
1018 my $fmt = $params{'snapshot_format'};
1019 # snapshot_format should always be defined when href()
1020 # is called, but just in case some code forgets, we
1021 # fall back to the default
1022 $fmt ||= $snapshot_fmts[0];
1023 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1024 delete $params{'snapshot_format'};
1028 # now encode the parameters explicitly
1029 my @result = ();
1030 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1031 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1032 if (defined $params{$name}) {
1033 if (ref($params{$name}) eq "ARRAY") {
1034 foreach my $par (@{$params{$name}}) {
1035 push @result, $symbol . "=" . esc_param($par);
1037 } else {
1038 push @result, $symbol . "=" . esc_param($params{$name});
1042 $href .= "?" . join(';', @result) if $params{-partial_query} or scalar @result;
1044 return $href;
1048 ## ======================================================================
1049 ## validation, quoting/unquoting and escaping
1051 sub validate_action {
1052 my $input = shift || return undef;
1053 return undef unless exists $actions{$input};
1054 return $input;
1057 sub validate_project {
1058 my $input = shift || return undef;
1059 if (!validate_pathname($input) ||
1060 !(-d "$projectroot/$input") ||
1061 !check_export_ok("$projectroot/$input") ||
1062 ($strict_export && !project_in_list($input))) {
1063 return undef;
1064 } else {
1065 return $input;
1069 sub validate_pathname {
1070 my $input = shift || return undef;
1072 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1073 # at the beginning, at the end, and between slashes.
1074 # also this catches doubled slashes
1075 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1076 return undef;
1078 # no null characters
1079 if ($input =~ m!\0!) {
1080 return undef;
1082 return $input;
1085 sub validate_refname {
1086 my $input = shift || return undef;
1088 # textual hashes are O.K.
1089 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1090 return $input;
1092 # it must be correct pathname
1093 $input = validate_pathname($input)
1094 or return undef;
1095 # restrictions on ref name according to git-check-ref-format
1096 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1097 return undef;
1099 return $input;
1102 # decode sequences of octets in utf8 into Perl's internal form,
1103 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1104 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1105 sub to_utf8 {
1106 my $str = shift;
1107 if (utf8::valid($str)) {
1108 utf8::decode($str);
1109 return $str;
1110 } else {
1111 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1115 # quote unsafe chars, but keep the slash, even when it's not
1116 # correct, but quoted slashes look too horrible in bookmarks
1117 sub esc_param {
1118 my $str = shift;
1119 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1120 $str =~ s/ /\+/g;
1121 return $str;
1124 # quote unsafe chars in whole URL, so some charactrs cannot be quoted
1125 sub esc_url {
1126 my $str = shift;
1127 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&=])/sprintf("%%%02X", ord($1))/eg;
1128 $str =~ s/\+/%2B/g;
1129 $str =~ s/ /\+/g;
1130 return $str;
1133 # replace invalid utf8 character with SUBSTITUTION sequence
1134 sub esc_html {
1135 my $str = shift;
1136 my %opts = @_;
1138 $str = to_utf8($str);
1139 $str = $cgi->escapeHTML($str);
1140 if ($opts{'-nbsp'}) {
1141 $str =~ s/ /&nbsp;/g;
1143 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1144 return $str;
1147 # quote control characters and escape filename to HTML
1148 sub esc_path {
1149 my $str = shift;
1150 my %opts = @_;
1152 $str = to_utf8($str);
1153 $str = $cgi->escapeHTML($str);
1154 if ($opts{'-nbsp'}) {
1155 $str =~ s/ /&nbsp;/g;
1157 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1158 return $str;
1161 # Make control characters "printable", using character escape codes (CEC)
1162 sub quot_cec {
1163 my $cntrl = shift;
1164 my %opts = @_;
1165 my %es = ( # character escape codes, aka escape sequences
1166 "\t" => '\t', # tab (HT)
1167 "\n" => '\n', # line feed (LF)
1168 "\r" => '\r', # carrige return (CR)
1169 "\f" => '\f', # form feed (FF)
1170 "\b" => '\b', # backspace (BS)
1171 "\a" => '\a', # alarm (bell) (BEL)
1172 "\e" => '\e', # escape (ESC)
1173 "\013" => '\v', # vertical tab (VT)
1174 "\000" => '\0', # nul character (NUL)
1176 my $chr = ( (exists $es{$cntrl})
1177 ? $es{$cntrl}
1178 : sprintf('\%2x', ord($cntrl)) );
1179 if ($opts{-nohtml}) {
1180 return $chr;
1181 } else {
1182 return "<span class=\"cntrl\">$chr</span>";
1186 # Alternatively use unicode control pictures codepoints,
1187 # Unicode "printable representation" (PR)
1188 sub quot_upr {
1189 my $cntrl = shift;
1190 my %opts = @_;
1192 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1193 if ($opts{-nohtml}) {
1194 return $chr;
1195 } else {
1196 return "<span class=\"cntrl\">$chr</span>";
1200 # git may return quoted and escaped filenames
1201 sub unquote {
1202 my $str = shift;
1204 sub unq {
1205 my $seq = shift;
1206 my %es = ( # character escape codes, aka escape sequences
1207 't' => "\t", # tab (HT, TAB)
1208 'n' => "\n", # newline (NL)
1209 'r' => "\r", # return (CR)
1210 'f' => "\f", # form feed (FF)
1211 'b' => "\b", # backspace (BS)
1212 'a' => "\a", # alarm (bell) (BEL)
1213 'e' => "\e", # escape (ESC)
1214 'v' => "\013", # vertical tab (VT)
1217 if ($seq =~ m/^[0-7]{1,3}$/) {
1218 # octal char sequence
1219 return chr(oct($seq));
1220 } elsif (exists $es{$seq}) {
1221 # C escape sequence, aka character escape code
1222 return $es{$seq};
1224 # quoted ordinary character
1225 return $seq;
1228 if ($str =~ m/^"(.*)"$/) {
1229 # needs unquoting
1230 $str = $1;
1231 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1233 return $str;
1236 # escape tabs (convert tabs to spaces)
1237 sub untabify {
1238 my $line = shift;
1240 while ((my $pos = index($line, "\t")) != -1) {
1241 if (my $count = (8 - ($pos % 8))) {
1242 my $spaces = ' ' x $count;
1243 $line =~ s/\t/$spaces/;
1247 return $line;
1250 sub project_in_list {
1251 my $project = shift;
1252 my @list = git_get_projects_list();
1253 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1256 ## ----------------------------------------------------------------------
1257 ## HTML aware string manipulation
1259 # Try to chop given string on a word boundary between position
1260 # $len and $len+$add_len. If there is no word boundary there,
1261 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1262 # (marking chopped part) would be longer than given string.
1263 sub chop_str {
1264 my $str = shift;
1265 my $len = shift;
1266 my $add_len = shift || 10;
1267 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1269 # Make sure perl knows it is utf8 encoded so we don't
1270 # cut in the middle of a utf8 multibyte char.
1271 $str = to_utf8($str);
1273 # allow only $len chars, but don't cut a word if it would fit in $add_len
1274 # if it doesn't fit, cut it if it's still longer than the dots we would add
1275 # remove chopped character entities entirely
1277 # when chopping in the middle, distribute $len into left and right part
1278 # return early if chopping wouldn't make string shorter
1279 if ($where eq 'center') {
1280 return $str if ($len + 5 >= length($str)); # filler is length 5
1281 $len = int($len/2);
1282 } else {
1283 return $str if ($len + 4 >= length($str)); # filler is length 4
1286 # regexps: ending and beginning with word part up to $add_len
1287 my $endre = qr/.{$len}\w{0,$add_len}/;
1288 my $begre = qr/\w{0,$add_len}.{$len}/;
1290 if ($where eq 'left') {
1291 $str =~ m/^(.*?)($begre)$/;
1292 my ($lead, $body) = ($1, $2);
1293 if (length($lead) > 4) {
1294 $body =~ s/^[^;]*;// if ($lead =~ m/&[^;]*$/);
1295 $lead = " ...";
1297 return "$lead$body";
1299 } elsif ($where eq 'center') {
1300 $str =~ m/^($endre)(.*)$/;
1301 my ($left, $str) = ($1, $2);
1302 $str =~ m/^(.*?)($begre)$/;
1303 my ($mid, $right) = ($1, $2);
1304 if (length($mid) > 5) {
1305 $left =~ s/&[^;]*$//;
1306 $right =~ s/^[^;]*;// if ($mid =~ m/&[^;]*$/);
1307 $mid = " ... ";
1309 return "$left$mid$right";
1311 } else {
1312 $str =~ m/^($endre)(.*)$/;
1313 my $body = $1;
1314 my $tail = $2;
1315 if (length($tail) > 4) {
1316 $body =~ s/&[^;]*$//;
1317 $tail = "... ";
1319 return "$body$tail";
1323 # takes the same arguments as chop_str, but also wraps a <span> around the
1324 # result with a title attribute if it does get chopped. Additionally, the
1325 # string is HTML-escaped.
1326 sub chop_and_escape_str {
1327 my ($str) = @_;
1329 my $chopped = chop_str(@_);
1330 if ($chopped eq $str) {
1331 return esc_html($chopped);
1332 } else {
1333 $str =~ s/[[:cntrl:]]/?/g;
1334 return $cgi->span({-title=>$str}, esc_html($chopped));
1338 ## ----------------------------------------------------------------------
1339 ## functions returning short strings
1341 # CSS class for given age value (in seconds)
1342 sub age_class {
1343 my $age = shift;
1345 if (!defined $age) {
1346 return "noage";
1347 } elsif ($age < 60*60*2) {
1348 return "age0";
1349 } elsif ($age < 60*60*24*2) {
1350 return "age1";
1351 } else {
1352 return "age2";
1356 # convert age in seconds to "nn units ago" string
1357 sub age_string {
1358 my $age = shift;
1359 my $age_str;
1361 if ($age > 60*60*24*365*2) {
1362 $age_str = (int $age/60/60/24/365);
1363 $age_str .= " years ago";
1364 } elsif ($age > 60*60*24*(365/12)*2) {
1365 $age_str = int $age/60/60/24/(365/12);
1366 $age_str .= " months ago";
1367 } elsif ($age > 60*60*24*7*2) {
1368 $age_str = int $age/60/60/24/7;
1369 $age_str .= " weeks ago";
1370 } elsif ($age > 60*60*24*2) {
1371 $age_str = int $age/60/60/24;
1372 $age_str .= " days ago";
1373 } elsif ($age > 60*60*2) {
1374 $age_str = int $age/60/60;
1375 $age_str .= " hours ago";
1376 } elsif ($age > 60*2) {
1377 $age_str = int $age/60;
1378 $age_str .= " min ago";
1379 } elsif ($age > 2) {
1380 $age_str = int $age;
1381 $age_str .= " sec ago";
1382 } else {
1383 $age_str .= " right now";
1385 return $age_str;
1388 use constant {
1389 S_IFINVALID => 0030000,
1390 S_IFGITLINK => 0160000,
1393 # submodule/subproject, a commit object reference
1394 sub S_ISGITLINK {
1395 my $mode = shift;
1397 return (($mode & S_IFMT) == S_IFGITLINK)
1400 # convert file mode in octal to symbolic file mode string
1401 sub mode_str {
1402 my $mode = oct shift;
1404 if (S_ISGITLINK($mode)) {
1405 return 'm---------';
1406 } elsif (S_ISDIR($mode & S_IFMT)) {
1407 return 'drwxr-xr-x';
1408 } elsif (S_ISLNK($mode)) {
1409 return 'lrwxrwxrwx';
1410 } elsif (S_ISREG($mode)) {
1411 # git cares only about the executable bit
1412 if ($mode & S_IXUSR) {
1413 return '-rwxr-xr-x';
1414 } else {
1415 return '-rw-r--r--';
1417 } else {
1418 return '----------';
1422 # convert file mode in octal to file type string
1423 sub file_type {
1424 my $mode = shift;
1426 if ($mode !~ m/^[0-7]+$/) {
1427 return $mode;
1428 } else {
1429 $mode = oct $mode;
1432 if (S_ISGITLINK($mode)) {
1433 return "submodule";
1434 } elsif (S_ISDIR($mode & S_IFMT)) {
1435 return "directory";
1436 } elsif (S_ISLNK($mode)) {
1437 return "symlink";
1438 } elsif (S_ISREG($mode)) {
1439 return "file";
1440 } else {
1441 return "unknown";
1445 # convert file mode in octal to file type description string
1446 sub file_type_long {
1447 my $mode = shift;
1449 if ($mode !~ m/^[0-7]+$/) {
1450 return $mode;
1451 } else {
1452 $mode = oct $mode;
1455 if (S_ISGITLINK($mode)) {
1456 return "submodule";
1457 } elsif (S_ISDIR($mode & S_IFMT)) {
1458 return "directory";
1459 } elsif (S_ISLNK($mode)) {
1460 return "symlink";
1461 } elsif (S_ISREG($mode)) {
1462 if ($mode & S_IXUSR) {
1463 return "executable";
1464 } else {
1465 return "file";
1467 } else {
1468 return "unknown";
1473 ## ----------------------------------------------------------------------
1474 ## functions returning short HTML fragments, or transforming HTML fragments
1475 ## which don't belong to other sections
1477 # format line of commit message.
1478 sub format_log_line_html {
1479 my $line = shift;
1481 $line = esc_html($line, -nbsp=>1);
1482 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1483 $cgi->a({-href => href(action=>"object", hash=>$1),
1484 -class => "text"}, $1);
1485 }eg;
1487 return $line;
1490 # format marker of refs pointing to given object
1492 # the destination action is chosen based on object type and current context:
1493 # - for annotated tags, we choose the tag view unless it's the current view
1494 # already, in which case we go to shortlog view
1495 # - for other refs, we keep the current view if we're in history, shortlog or
1496 # log view, and select shortlog otherwise
1497 sub format_ref_marker {
1498 my ($refs, $id) = @_;
1499 my $markers = '';
1501 if (defined $refs->{$id}) {
1502 foreach my $ref (@{$refs->{$id}}) {
1503 # this code exploits the fact that non-lightweight tags are the
1504 # only indirect objects, and that they are the only objects for which
1505 # we want to use tag instead of shortlog as action
1506 my ($type, $name) = qw();
1507 my $indirect = ($ref =~ s/\^\{\}$//);
1508 # e.g. tags/v2.6.11 or heads/next
1509 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1510 $type = $1;
1511 $name = $2;
1512 } else {
1513 $type = "ref";
1514 $name = $ref;
1517 my $class = $type;
1518 $class .= " indirect" if $indirect;
1520 my $dest_action = "shortlog";
1522 if ($indirect) {
1523 $dest_action = "tag" unless $action eq "tag";
1524 } elsif ($action =~ /^(history|(short)?log)$/) {
1525 $dest_action = $action;
1528 my $dest = "";
1529 $dest .= "refs/" unless $ref =~ m!^refs/!;
1530 $dest .= $ref;
1532 my $link = $cgi->a({
1533 -href => href(
1534 action=>$dest_action,
1535 hash=>$dest
1536 )}, $name);
1538 $markers .= " <span class=\"$class\" title=\"$ref\">" .
1539 $link . "</span>";
1543 if ($markers) {
1544 return ' <span class="refs">'. $markers . '</span>';
1545 } else {
1546 return "";
1550 # format, perhaps shortened and with markers, title line
1551 sub format_subject_html {
1552 my ($long, $short, $href, $extra) = @_;
1553 $extra = '' unless defined($extra);
1555 if (length($short) < length($long)) {
1556 $long =~ s/[[:cntrl:]]/?/g;
1557 return $cgi->a({-href => $href, -class => "list subject",
1558 -title => to_utf8($long)},
1559 esc_html($short)) . $extra;
1560 } else {
1561 return $cgi->a({-href => $href, -class => "list subject"},
1562 esc_html($long)) . $extra;
1566 # Rather than recomputing the url for an email multiple times, we cache it
1567 # after the first hit. This gives a visible benefit in views where the avatar
1568 # for the same email is used repeatedly (e.g. shortlog).
1569 # The cache is shared by all avatar engines (currently gravatar only), which
1570 # are free to use it as preferred. Since only one avatar engine is used for any
1571 # given page, there's no risk for cache conflicts.
1572 our %avatar_cache = ();
1574 # Compute the picon url for a given email, by using the picon search service over at
1575 # http://www.cs.indiana.edu/picons/search.html
1576 sub picon_url {
1577 my $email = lc shift;
1578 if (!$avatar_cache{$email}) {
1579 my ($user, $domain) = split('@', $email);
1580 $avatar_cache{$email} =
1581 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1582 "$domain/$user/" .
1583 "users+domains+unknown/up/single";
1585 return $avatar_cache{$email};
1588 # Compute the gravatar url for a given email, if it's not in the cache already.
1589 # Gravatar stores only the part of the URL before the size, since that's the
1590 # one computationally more expensive. This also allows reuse of the cache for
1591 # different sizes (for this particular engine).
1592 sub gravatar_url {
1593 my $email = lc shift;
1594 my $size = shift;
1595 $avatar_cache{$email} ||=
1596 "http://www.gravatar.com/avatar/" .
1597 Digest::MD5::md5_hex($email) . "?s=";
1598 return $avatar_cache{$email} . $size;
1601 # Insert an avatar for the given $email at the given $size if the feature
1602 # is enabled.
1603 sub git_get_avatar {
1604 my ($email, %opts) = @_;
1605 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
1606 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
1607 $opts{-size} ||= 'default';
1608 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1609 my $url = "";
1610 if ($git_avatar eq 'gravatar') {
1611 $url = gravatar_url($email, $size);
1612 } elsif ($git_avatar eq 'picon') {
1613 $url = picon_url($email);
1615 # Other providers can be added by extending the if chain, defining $url
1616 # as needed. If no variant puts something in $url, we assume avatars
1617 # are completely disabled/unavailable.
1618 if ($url) {
1619 return $pre_white .
1620 "<img width=\"$size\" " .
1621 "class=\"avatar\" " .
1622 "src=\"$url\" " .
1623 "alt=\"\" " .
1624 "/>" . $post_white;
1625 } else {
1626 return "";
1630 sub format_search_author {
1631 my ($author, $searchtype, $displaytext) = @_;
1632 my $have_search = gitweb_check_feature('search');
1634 if ($have_search) {
1635 my $performed = "";
1636 if ($searchtype eq 'author') {
1637 $performed = "authored";
1638 } elsif ($searchtype eq 'committer') {
1639 $performed = "committed";
1642 return $cgi->a({-href => href(action=>"search", hash=>$hash,
1643 searchtext=>$author,
1644 searchtype=>$searchtype), class=>"list",
1645 title=>"Search for commits $performed by $author"},
1646 $displaytext);
1648 } else {
1649 return $displaytext;
1653 # format the author name of the given commit with the given tag
1654 # the author name is chopped and escaped according to the other
1655 # optional parameters (see chop_str).
1656 sub format_author_html {
1657 my $tag = shift;
1658 my $co = shift;
1659 my $author = chop_and_escape_str($co->{'author_name'}, @_);
1660 return "<$tag class=\"author\">" .
1661 format_search_author($co->{'author_name'}, "author",
1662 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
1663 $author) .
1664 "</$tag>";
1667 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
1668 sub format_git_diff_header_line {
1669 my $line = shift;
1670 my $diffinfo = shift;
1671 my ($from, $to) = @_;
1673 if ($diffinfo->{'nparents'}) {
1674 # combined diff
1675 $line =~ s!^(diff (.*?) )"?.*$!$1!;
1676 if ($to->{'href'}) {
1677 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1678 esc_path($to->{'file'}));
1679 } else { # file was deleted (no href)
1680 $line .= esc_path($to->{'file'});
1682 } else {
1683 # "ordinary" diff
1684 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
1685 if ($from->{'href'}) {
1686 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
1687 'a/' . esc_path($from->{'file'}));
1688 } else { # file was added (no href)
1689 $line .= 'a/' . esc_path($from->{'file'});
1691 $line .= ' ';
1692 if ($to->{'href'}) {
1693 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
1694 'b/' . esc_path($to->{'file'}));
1695 } else { # file was deleted
1696 $line .= 'b/' . esc_path($to->{'file'});
1700 return "<div class=\"diff header\">$line</div>\n";
1703 # format extended diff header line, before patch itself
1704 sub format_extended_diff_header_line {
1705 my $line = shift;
1706 my $diffinfo = shift;
1707 my ($from, $to) = @_;
1709 # match <path>
1710 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
1711 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1712 esc_path($from->{'file'}));
1714 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
1715 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1716 esc_path($to->{'file'}));
1718 # match single <mode>
1719 if ($line =~ m/\s(\d{6})$/) {
1720 $line .= '<span class="info"> (' .
1721 file_type_long($1) .
1722 ')</span>';
1724 # match <hash>
1725 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
1726 # can match only for combined diff
1727 $line = 'index ';
1728 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1729 if ($from->{'href'}[$i]) {
1730 $line .= $cgi->a({-href=>$from->{'href'}[$i],
1731 -class=>"hash"},
1732 substr($diffinfo->{'from_id'}[$i],0,7));
1733 } else {
1734 $line .= '0' x 7;
1736 # separator
1737 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
1739 $line .= '..';
1740 if ($to->{'href'}) {
1741 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1742 substr($diffinfo->{'to_id'},0,7));
1743 } else {
1744 $line .= '0' x 7;
1747 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
1748 # can match only for ordinary diff
1749 my ($from_link, $to_link);
1750 if ($from->{'href'}) {
1751 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
1752 substr($diffinfo->{'from_id'},0,7));
1753 } else {
1754 $from_link = '0' x 7;
1756 if ($to->{'href'}) {
1757 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
1758 substr($diffinfo->{'to_id'},0,7));
1759 } else {
1760 $to_link = '0' x 7;
1762 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
1763 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
1766 return $line . "<br/>\n";
1769 # format from-file/to-file diff header
1770 sub format_diff_from_to_header {
1771 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
1772 my $line;
1773 my $result = '';
1775 $line = $from_line;
1776 #assert($line =~ m/^---/) if DEBUG;
1777 # no extra formatting for "^--- /dev/null"
1778 if (! $diffinfo->{'nparents'}) {
1779 # ordinary (single parent) diff
1780 if ($line =~ m!^--- "?a/!) {
1781 if ($from->{'href'}) {
1782 $line = '--- a/' .
1783 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
1784 esc_path($from->{'file'}));
1785 } else {
1786 $line = '--- a/' .
1787 esc_path($from->{'file'});
1790 $result .= qq!<div class="diff from_file">$line</div>\n!;
1792 } else {
1793 # combined diff (merge commit)
1794 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
1795 if ($from->{'href'}[$i]) {
1796 $line = '--- ' .
1797 $cgi->a({-href=>href(action=>"blobdiff",
1798 hash_parent=>$diffinfo->{'from_id'}[$i],
1799 hash_parent_base=>$parents[$i],
1800 file_parent=>$from->{'file'}[$i],
1801 hash=>$diffinfo->{'to_id'},
1802 hash_base=>$hash,
1803 file_name=>$to->{'file'}),
1804 -class=>"path",
1805 -title=>"diff" . ($i+1)},
1806 $i+1) .
1807 '/' .
1808 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
1809 esc_path($from->{'file'}[$i]));
1810 } else {
1811 $line = '--- /dev/null';
1813 $result .= qq!<div class="diff from_file">$line</div>\n!;
1817 $line = $to_line;
1818 #assert($line =~ m/^\+\+\+/) if DEBUG;
1819 # no extra formatting for "^+++ /dev/null"
1820 if ($line =~ m!^\+\+\+ "?b/!) {
1821 if ($to->{'href'}) {
1822 $line = '+++ b/' .
1823 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
1824 esc_path($to->{'file'}));
1825 } else {
1826 $line = '+++ b/' .
1827 esc_path($to->{'file'});
1830 $result .= qq!<div class="diff to_file">$line</div>\n!;
1832 return $result;
1835 # create note for patch simplified by combined diff
1836 sub format_diff_cc_simplified {
1837 my ($diffinfo, @parents) = @_;
1838 my $result = '';
1840 $result .= "<div class=\"diff header\">" .
1841 "diff --cc ";
1842 if (!is_deleted($diffinfo)) {
1843 $result .= $cgi->a({-href => href(action=>"blob",
1844 hash_base=>$hash,
1845 hash=>$diffinfo->{'to_id'},
1846 file_name=>$diffinfo->{'to_file'}),
1847 -class => "path"},
1848 esc_path($diffinfo->{'to_file'}));
1849 } else {
1850 $result .= esc_path($diffinfo->{'to_file'});
1852 $result .= "</div>\n" . # class="diff header"
1853 "<div class=\"diff nodifferences\">" .
1854 "Simple merge" .
1855 "</div>\n"; # class="diff nodifferences"
1857 return $result;
1860 # format patch (diff) line (not to be used for diff headers)
1861 sub format_diff_line {
1862 my $line = shift;
1863 my ($from, $to) = @_;
1864 my $diff_class = "";
1866 chomp $line;
1868 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
1869 # combined diff
1870 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
1871 if ($line =~ m/^\@{3}/) {
1872 $diff_class = " chunk_header";
1873 } elsif ($line =~ m/^\\/) {
1874 $diff_class = " incomplete";
1875 } elsif ($prefix =~ tr/+/+/) {
1876 $diff_class = " add";
1877 } elsif ($prefix =~ tr/-/-/) {
1878 $diff_class = " rem";
1880 } else {
1881 # assume ordinary diff
1882 my $char = substr($line, 0, 1);
1883 if ($char eq '+') {
1884 $diff_class = " add";
1885 } elsif ($char eq '-') {
1886 $diff_class = " rem";
1887 } elsif ($char eq '@') {
1888 $diff_class = " chunk_header";
1889 } elsif ($char eq "\\") {
1890 $diff_class = " incomplete";
1893 $line = untabify($line);
1894 if ($from && $to && $line =~ m/^\@{2} /) {
1895 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
1896 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
1898 $from_lines = 0 unless defined $from_lines;
1899 $to_lines = 0 unless defined $to_lines;
1901 if ($from->{'href'}) {
1902 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
1903 -class=>"list"}, $from_text);
1905 if ($to->{'href'}) {
1906 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
1907 -class=>"list"}, $to_text);
1909 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
1910 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1911 return "<div class=\"diff$diff_class\">$line</div>\n";
1912 } elsif ($from && $to && $line =~ m/^\@{3}/) {
1913 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
1914 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
1916 @from_text = split(' ', $ranges);
1917 for (my $i = 0; $i < @from_text; ++$i) {
1918 ($from_start[$i], $from_nlines[$i]) =
1919 (split(',', substr($from_text[$i], 1)), 0);
1922 $to_text = pop @from_text;
1923 $to_start = pop @from_start;
1924 $to_nlines = pop @from_nlines;
1926 $line = "<span class=\"chunk_info\">$prefix ";
1927 for (my $i = 0; $i < @from_text; ++$i) {
1928 if ($from->{'href'}[$i]) {
1929 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
1930 -class=>"list"}, $from_text[$i]);
1931 } else {
1932 $line .= $from_text[$i];
1934 $line .= " ";
1936 if ($to->{'href'}) {
1937 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
1938 -class=>"list"}, $to_text);
1939 } else {
1940 $line .= $to_text;
1942 $line .= " $prefix</span>" .
1943 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
1944 return "<div class=\"diff$diff_class\">$line</div>\n";
1946 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
1949 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
1950 # linked. Pass the hash of the tree/commit to snapshot.
1951 sub format_snapshot_links {
1952 my ($hash) = @_;
1953 my $num_fmts = @snapshot_fmts;
1954 if ($num_fmts > 1) {
1955 # A parenthesized list of links bearing format names.
1956 # e.g. "snapshot (_tar.gz_ _zip_)"
1957 return "snapshot (" . join(' ', map
1958 $cgi->a({
1959 -href => href(
1960 action=>"snapshot",
1961 hash=>$hash,
1962 snapshot_format=>$_
1964 }, $known_snapshot_formats{$_}{'display'})
1965 , @snapshot_fmts) . ")";
1966 } elsif ($num_fmts == 1) {
1967 # A single "snapshot" link whose tooltip bears the format name.
1968 # i.e. "_snapshot_"
1969 my ($fmt) = @snapshot_fmts;
1970 return
1971 $cgi->a({
1972 -href => href(
1973 action=>"snapshot",
1974 hash=>$hash,
1975 snapshot_format=>$fmt
1977 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
1978 }, "snapshot");
1979 } else { # $num_fmts == 0
1980 return undef;
1984 ## ......................................................................
1985 ## functions returning values to be passed, perhaps after some
1986 ## transformation, to other functions; e.g. returning arguments to href()
1988 # returns hash to be passed to href to generate gitweb URL
1989 # in -title key it returns description of link
1990 sub get_feed_info {
1991 my $format = shift || 'Atom';
1992 my %res = (action => lc($format));
1994 # feed links are possible only for project views
1995 return unless (defined $project);
1996 # some views should link to OPML, or to generic project feed,
1997 # or don't have specific feed yet (so they should use generic)
1998 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
2000 my $branch;
2001 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2002 # from tag links; this also makes possible to detect branch links
2003 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2004 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2005 $branch = $1;
2007 # find log type for feed description (title)
2008 my $type = 'log';
2009 if (defined $file_name) {
2010 $type = "history of $file_name";
2011 $type .= "/" if ($action eq 'tree');
2012 $type .= " on '$branch'" if (defined $branch);
2013 } else {
2014 $type = "log of $branch" if (defined $branch);
2017 $res{-title} = $type;
2018 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2019 $res{'file_name'} = $file_name;
2021 return %res;
2024 ## ----------------------------------------------------------------------
2025 ## git utility subroutines, invoking git commands
2027 # returns path to the core git executable and the --git-dir parameter as list
2028 sub git_cmd {
2029 return $GIT, '--git-dir='.$git_dir;
2032 # quote the given arguments for passing them to the shell
2033 # quote_command("command", "arg 1", "arg with ' and ! characters")
2034 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2035 # Try to avoid using this function wherever possible.
2036 sub quote_command {
2037 return join(' ',
2038 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2041 # get HEAD ref of given project as hash
2042 sub git_get_head_hash {
2043 my $project = shift;
2044 my $o_git_dir = $git_dir;
2045 my $retval = undef;
2046 $git_dir = "$projectroot/$project";
2047 if (open my $fd, "-|", git_cmd(), "rev-parse", "--verify", "HEAD") {
2048 my $head = <$fd>;
2049 close $fd;
2050 if (defined $head && $head =~ /^([0-9a-fA-F]{40})$/) {
2051 $retval = $1;
2054 if (defined $o_git_dir) {
2055 $git_dir = $o_git_dir;
2057 return $retval;
2060 # get type of given object
2061 sub git_get_type {
2062 my $hash = shift;
2064 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2065 my $type = <$fd>;
2066 close $fd or return;
2067 chomp $type;
2068 return $type;
2071 # repository configuration
2072 our $config_file = '';
2073 our %config;
2075 # store multiple values for single key as anonymous array reference
2076 # single values stored directly in the hash, not as [ <value> ]
2077 sub hash_set_multi {
2078 my ($hash, $key, $value) = @_;
2080 if (!exists $hash->{$key}) {
2081 $hash->{$key} = $value;
2082 } elsif (!ref $hash->{$key}) {
2083 $hash->{$key} = [ $hash->{$key}, $value ];
2084 } else {
2085 push @{$hash->{$key}}, $value;
2089 # return hash of git project configuration
2090 # optionally limited to some section, e.g. 'gitweb'
2091 sub git_parse_project_config {
2092 my $section_regexp = shift;
2093 my %config;
2095 local $/ = "\0";
2097 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2098 or return;
2100 while (my $keyval = <$fh>) {
2101 chomp $keyval;
2102 my ($key, $value) = split(/\n/, $keyval, 2);
2104 hash_set_multi(\%config, $key, $value)
2105 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2107 close $fh;
2109 return %config;
2112 # convert config value to boolean: 'true' or 'false'
2113 # no value, number > 0, 'true' and 'yes' values are true
2114 # rest of values are treated as false (never as error)
2115 sub config_to_bool {
2116 my $val = shift;
2118 return 1 if !defined $val; # section.key
2120 # strip leading and trailing whitespace
2121 $val =~ s/^\s+//;
2122 $val =~ s/\s+$//;
2124 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2125 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2128 # convert config value to simple decimal number
2129 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2130 # to be multiplied by 1024, 1048576, or 1073741824
2131 sub config_to_int {
2132 my $val = shift;
2134 # strip leading and trailing whitespace
2135 $val =~ s/^\s+//;
2136 $val =~ s/\s+$//;
2138 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2139 $unit = lc($unit);
2140 # unknown unit is treated as 1
2141 return $num * ($unit eq 'g' ? 1073741824 :
2142 $unit eq 'm' ? 1048576 :
2143 $unit eq 'k' ? 1024 : 1);
2145 return $val;
2148 # convert config value to array reference, if needed
2149 sub config_to_multi {
2150 my $val = shift;
2152 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2155 sub git_get_project_config {
2156 my ($key, $type) = @_;
2158 # key sanity check
2159 return unless ($key);
2160 $key =~ s/^gitweb\.//;
2161 return if ($key =~ m/\W/);
2163 # type sanity check
2164 if (defined $type) {
2165 $type =~ s/^--//;
2166 $type = undef
2167 unless ($type eq 'bool' || $type eq 'int');
2170 # get config
2171 if (!defined $config_file ||
2172 $config_file ne "$git_dir/config") {
2173 %config = git_parse_project_config('gitweb');
2174 $config_file = "$git_dir/config";
2177 # check if config variable (key) exists
2178 return unless exists $config{"gitweb.$key"};
2180 # ensure given type
2181 if (!defined $type) {
2182 return $config{"gitweb.$key"};
2183 } elsif ($type eq 'bool') {
2184 # backward compatibility: 'git config --bool' returns true/false
2185 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2186 } elsif ($type eq 'int') {
2187 return config_to_int($config{"gitweb.$key"});
2189 return $config{"gitweb.$key"};
2192 # get hash of given path at given ref
2193 sub git_get_hash_by_path {
2194 my $base = shift;
2195 my $path = shift || return undef;
2196 my $type = shift;
2198 $path =~ s,/+$,,;
2200 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2201 or die_error(500, "Open git-ls-tree failed");
2202 my $line = <$fd>;
2203 close $fd or return undef;
2205 if (!defined $line) {
2206 # there is no tree or hash given by $path at $base
2207 return undef;
2210 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2211 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2212 if (defined $type && $type ne $2) {
2213 # type doesn't match
2214 return undef;
2216 return $3;
2219 # get path of entry with given hash at given tree-ish (ref)
2220 # used to get 'from' filename for combined diff (merge commit) for renames
2221 sub git_get_path_by_hash {
2222 my $base = shift || return;
2223 my $hash = shift || return;
2225 local $/ = "\0";
2227 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2228 or return undef;
2229 while (my $line = <$fd>) {
2230 chomp $line;
2232 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2233 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2234 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2235 close $fd;
2236 return $1;
2239 close $fd;
2240 return undef;
2243 ## ......................................................................
2244 ## git utility functions, directly accessing git repository
2246 sub git_get_project_description {
2247 my $path = shift;
2249 $git_dir = "$projectroot/$path";
2250 open my $fd, '<', "$git_dir/description"
2251 or return git_get_project_config('description');
2252 my $descr = <$fd>;
2253 close $fd;
2254 if (defined $descr) {
2255 chomp $descr;
2257 return $descr;
2260 sub git_get_project_ctags {
2261 my $path = shift;
2262 my $ctags = {};
2264 $git_dir = "$projectroot/$path";
2265 opendir my $dh, "$git_dir/ctags"
2266 or return $ctags;
2267 foreach (grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh)) {
2268 open my $ct, '<', $_ or next;
2269 my $val = <$ct>;
2270 chomp $val;
2271 close $ct;
2272 my $ctag = $_; $ctag =~ s#.*/##;
2273 $ctags->{$ctag} = $val;
2275 closedir $dh;
2276 $ctags;
2279 sub git_populate_project_tagcloud {
2280 my $ctags = shift;
2282 # First, merge different-cased tags; tags vote on casing
2283 my %ctags_lc;
2284 foreach (keys %$ctags) {
2285 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2286 if (not $ctags_lc{lc $_}->{topcount}
2287 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2288 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2289 $ctags_lc{lc $_}->{topname} = $_;
2293 my $cloud;
2294 if (eval { require HTML::TagCloud; 1; }) {
2295 $cloud = HTML::TagCloud->new;
2296 foreach (sort keys %ctags_lc) {
2297 # Pad the title with spaces so that the cloud looks
2298 # less crammed.
2299 my $title = $ctags_lc{$_}->{topname};
2300 $title =~ s/ /&nbsp;/g;
2301 $title =~ s/^/&nbsp;/g;
2302 $title =~ s/$/&nbsp;/g;
2303 $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count});
2305 } else {
2306 $cloud = \%ctags_lc;
2308 $cloud;
2311 sub git_show_project_tagcloud {
2312 my ($cloud, $count) = @_;
2313 print STDERR ref($cloud)."..\n";
2314 if (ref $cloud eq 'HTML::TagCloud') {
2315 return $cloud->html_and_css($count);
2316 } else {
2317 my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud;
2318 return '<p align="center">' . join (', ', map {
2319 "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>"
2320 } splice(@tags, 0, $count)) . '</p>';
2324 sub git_get_project_url_list {
2325 my $path = shift;
2327 $git_dir = "$projectroot/$path";
2328 open my $fd, '<', "$git_dir/cloneurl"
2329 or return wantarray ?
2330 @{ config_to_multi(git_get_project_config('url')) } :
2331 config_to_multi(git_get_project_config('url'));
2332 my @git_project_url_list = map { chomp; $_ } <$fd>;
2333 close $fd;
2335 return wantarray ? @git_project_url_list : \@git_project_url_list;
2338 sub git_get_projects_list {
2339 my ($filter) = @_;
2340 my @list;
2342 $filter ||= '';
2343 $filter =~ s/\.git$//;
2345 my $check_forks = gitweb_check_feature('forks');
2347 if (-d $projects_list) {
2348 # search in directory
2349 my $dir = $projects_list . ($filter ? "/$filter" : '');
2350 # remove the trailing "/"
2351 $dir =~ s!/+$!!;
2352 my $pfxlen = length("$dir");
2353 my $pfxdepth = ($dir =~ tr!/!!);
2355 File::Find::find({
2356 follow_fast => 1, # follow symbolic links
2357 follow_skip => 2, # ignore duplicates
2358 dangling_symlinks => 0, # ignore dangling symlinks, silently
2359 wanted => sub {
2360 # skip project-list toplevel, if we get it.
2361 return if (m!^[/.]$!);
2362 # only directories can be git repositories
2363 return unless (-d $_);
2364 # don't traverse too deep (Find is super slow on os x)
2365 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2366 $File::Find::prune = 1;
2367 return;
2370 my $subdir = substr($File::Find::name, $pfxlen + 1);
2371 # we check related file in $projectroot
2372 my $path = ($filter ? "$filter/" : '') . $subdir;
2373 if (check_export_ok("$projectroot/$path")) {
2374 push @list, { path => $path };
2375 $File::Find::prune = 1;
2378 }, "$dir");
2380 } elsif (-f $projects_list) {
2381 # read from file(url-encoded):
2382 # 'git%2Fgit.git Linus+Torvalds'
2383 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2384 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2385 my %paths;
2386 open my $fd, '<', $projects_list or return;
2387 PROJECT:
2388 while (my $line = <$fd>) {
2389 chomp $line;
2390 my ($path, $owner) = split ' ', $line;
2391 $path = unescape($path);
2392 $owner = unescape($owner);
2393 if (!defined $path) {
2394 next;
2396 if ($filter ne '') {
2397 # looking for forks;
2398 my $pfx = substr($path, 0, length($filter));
2399 if ($pfx ne $filter) {
2400 next PROJECT;
2402 my $sfx = substr($path, length($filter));
2403 if ($sfx !~ /^\/.*\.git$/) {
2404 next PROJECT;
2406 } elsif ($check_forks) {
2407 PATH:
2408 foreach my $filter (keys %paths) {
2409 # looking for forks;
2410 my $pfx = substr($path, 0, length($filter));
2411 if ($pfx ne $filter) {
2412 next PATH;
2414 my $sfx = substr($path, length($filter));
2415 if ($sfx !~ /^\/.*\.git$/) {
2416 next PATH;
2418 # is a fork, don't include it in
2419 # the list
2420 next PROJECT;
2423 if (check_export_ok("$projectroot/$path")) {
2424 my $pr = {
2425 path => $path,
2426 owner => to_utf8($owner),
2428 push @list, $pr;
2429 (my $forks_path = $path) =~ s/\.git$//;
2430 $paths{$forks_path}++;
2433 close $fd;
2435 return @list;
2438 our $gitweb_project_owner = undef;
2439 sub git_get_project_list_from_file {
2441 return if (defined $gitweb_project_owner);
2443 $gitweb_project_owner = {};
2444 # read from file (url-encoded):
2445 # 'git%2Fgit.git Linus+Torvalds'
2446 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2447 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2448 if (-f $projects_list) {
2449 open(my $fd, '<', $projects_list);
2450 while (my $line = <$fd>) {
2451 chomp $line;
2452 my ($pr, $ow) = split ' ', $line;
2453 $pr = unescape($pr);
2454 $ow = unescape($ow);
2455 $gitweb_project_owner->{$pr} = to_utf8($ow);
2457 close $fd;
2461 sub git_get_project_owner {
2462 my $project = shift;
2463 my $owner;
2465 return undef unless $project;
2466 $git_dir = "$projectroot/$project";
2468 if (!defined $gitweb_project_owner) {
2469 git_get_project_list_from_file();
2472 if (exists $gitweb_project_owner->{$project}) {
2473 $owner = $gitweb_project_owner->{$project};
2475 if (!defined $owner){
2476 $owner = git_get_project_config('owner');
2478 if (!defined $owner) {
2479 $owner = get_file_owner("$git_dir");
2482 return $owner;
2485 sub git_get_last_activity {
2486 my ($path) = @_;
2487 my $fd;
2489 $git_dir = "$projectroot/$path";
2490 open($fd, "-|", git_cmd(), 'for-each-ref',
2491 '--format=%(committer)',
2492 '--sort=-committerdate',
2493 '--count=1',
2494 'refs/heads') or return;
2495 my $most_recent = <$fd>;
2496 close $fd or return;
2497 if (defined $most_recent &&
2498 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
2499 my $timestamp = $1;
2500 my $age = time - $timestamp;
2501 return ($age, age_string($age));
2503 return (undef, undef);
2506 sub git_get_references {
2507 my $type = shift || "";
2508 my %refs;
2509 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
2510 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
2511 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
2512 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
2513 or return;
2515 while (my $line = <$fd>) {
2516 chomp $line;
2517 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
2518 if (defined $refs{$1}) {
2519 push @{$refs{$1}}, $2;
2520 } else {
2521 $refs{$1} = [ $2 ];
2525 close $fd or return;
2526 return \%refs;
2529 sub git_get_rev_name_tags {
2530 my $hash = shift || return undef;
2532 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
2533 or return;
2534 my $name_rev = <$fd>;
2535 close $fd;
2537 if ($name_rev =~ m|^$hash tags/(.*)$|) {
2538 return $1;
2539 } else {
2540 # catches also '$hash undefined' output
2541 return undef;
2545 ## ----------------------------------------------------------------------
2546 ## parse to hash functions
2548 sub parse_date {
2549 my $epoch = shift;
2550 my $tz = shift || "-0000";
2552 my %date;
2553 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
2554 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
2555 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
2556 $date{'hour'} = $hour;
2557 $date{'minute'} = $min;
2558 $date{'mday'} = $mday;
2559 $date{'day'} = $days[$wday];
2560 $date{'month'} = $months[$mon];
2561 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
2562 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
2563 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
2564 $mday, $months[$mon], $hour ,$min;
2565 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
2566 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
2568 $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
2569 my $local = $epoch + ((int $1 + ($2/60)) * 3600);
2570 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
2571 $date{'hour_local'} = $hour;
2572 $date{'minute_local'} = $min;
2573 $date{'tz_local'} = $tz;
2574 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
2575 1900+$year, $mon+1, $mday,
2576 $hour, $min, $sec, $tz);
2577 return %date;
2580 sub parse_tag {
2581 my $tag_id = shift;
2582 my %tag;
2583 my @comment;
2585 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
2586 $tag{'id'} = $tag_id;
2587 while (my $line = <$fd>) {
2588 chomp $line;
2589 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
2590 $tag{'object'} = $1;
2591 } elsif ($line =~ m/^type (.+)$/) {
2592 $tag{'type'} = $1;
2593 } elsif ($line =~ m/^tag (.+)$/) {
2594 $tag{'name'} = $1;
2595 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
2596 $tag{'author'} = $1;
2597 $tag{'author_epoch'} = $2;
2598 $tag{'author_tz'} = $3;
2599 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2600 $tag{'author_name'} = $1;
2601 $tag{'author_email'} = $2;
2602 } else {
2603 $tag{'author_name'} = $tag{'author'};
2605 } elsif ($line =~ m/--BEGIN/) {
2606 push @comment, $line;
2607 last;
2608 } elsif ($line eq "") {
2609 last;
2612 push @comment, <$fd>;
2613 $tag{'comment'} = \@comment;
2614 close $fd or return;
2615 if (!defined $tag{'name'}) {
2616 return
2618 return %tag
2621 sub parse_commit_text {
2622 my ($commit_text, $withparents) = @_;
2623 my @commit_lines = split '\n', $commit_text;
2624 my %co;
2626 pop @commit_lines; # Remove '\0'
2628 if (! @commit_lines) {
2629 return;
2632 my $header = shift @commit_lines;
2633 if ($header !~ m/^[0-9a-fA-F]{40}/) {
2634 return;
2636 ($co{'id'}, my @parents) = split ' ', $header;
2637 while (my $line = shift @commit_lines) {
2638 last if $line eq "\n";
2639 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
2640 $co{'tree'} = $1;
2641 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
2642 push @parents, $1;
2643 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
2644 $co{'author'} = to_utf8($1);
2645 $co{'author_epoch'} = $2;
2646 $co{'author_tz'} = $3;
2647 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
2648 $co{'author_name'} = $1;
2649 $co{'author_email'} = $2;
2650 } else {
2651 $co{'author_name'} = $co{'author'};
2653 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
2654 $co{'committer'} = to_utf8($1);
2655 $co{'committer_epoch'} = $2;
2656 $co{'committer_tz'} = $3;
2657 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
2658 $co{'committer_name'} = $1;
2659 $co{'committer_email'} = $2;
2660 } else {
2661 $co{'committer_name'} = $co{'committer'};
2665 if (!defined $co{'tree'}) {
2666 return;
2668 $co{'parents'} = \@parents;
2669 $co{'parent'} = $parents[0];
2671 foreach my $title (@commit_lines) {
2672 $title =~ s/^ //;
2673 if ($title ne "") {
2674 $co{'title'} = chop_str($title, 80, 5);
2675 # remove leading stuff of merges to make the interesting part visible
2676 if (length($title) > 50) {
2677 $title =~ s/^Automatic //;
2678 $title =~ s/^merge (of|with) /Merge ... /i;
2679 if (length($title) > 50) {
2680 $title =~ s/(http|rsync):\/\///;
2682 if (length($title) > 50) {
2683 $title =~ s/(master|www|rsync)\.//;
2685 if (length($title) > 50) {
2686 $title =~ s/kernel.org:?//;
2688 if (length($title) > 50) {
2689 $title =~ s/\/pub\/scm//;
2692 $co{'title_short'} = chop_str($title, 50, 5);
2693 last;
2696 if (! defined $co{'title'} || $co{'title'} eq "") {
2697 $co{'title'} = $co{'title_short'} = '(no commit message)';
2699 # remove added spaces
2700 foreach my $line (@commit_lines) {
2701 $line =~ s/^ //;
2703 $co{'comment'} = \@commit_lines;
2705 my $age = time - $co{'committer_epoch'};
2706 $co{'age'} = $age;
2707 $co{'age_string'} = age_string($age);
2708 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
2709 if ($age > 60*60*24*7*2) {
2710 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2711 $co{'age_string_age'} = $co{'age_string'};
2712 } else {
2713 $co{'age_string_date'} = $co{'age_string'};
2714 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2716 return %co;
2719 sub parse_commit {
2720 my ($commit_id) = @_;
2721 my %co;
2723 local $/ = "\0";
2725 open my $fd, "-|", git_cmd(), "rev-list",
2726 "--parents",
2727 "--header",
2728 "--max-count=1",
2729 $commit_id,
2730 "--",
2731 or die_error(500, "Open git-rev-list failed");
2732 %co = parse_commit_text(<$fd>, 1);
2733 close $fd;
2735 return %co;
2738 sub parse_commits {
2739 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
2740 my @cos;
2742 $maxcount ||= 1;
2743 $skip ||= 0;
2745 local $/ = "\0";
2747 open my $fd, "-|", git_cmd(), "rev-list",
2748 "--header",
2749 @args,
2750 ("--max-count=" . $maxcount),
2751 ("--skip=" . $skip),
2752 @extra_options,
2753 $commit_id,
2754 "--",
2755 ($filename ? ($filename) : ())
2756 or die_error(500, "Open git-rev-list failed");
2757 while (my $line = <$fd>) {
2758 my %co = parse_commit_text($line);
2759 push @cos, \%co;
2761 close $fd;
2763 return wantarray ? @cos : \@cos;
2766 # parse line of git-diff-tree "raw" output
2767 sub parse_difftree_raw_line {
2768 my $line = shift;
2769 my %res;
2771 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
2772 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
2773 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
2774 $res{'from_mode'} = $1;
2775 $res{'to_mode'} = $2;
2776 $res{'from_id'} = $3;
2777 $res{'to_id'} = $4;
2778 $res{'status'} = $5;
2779 $res{'similarity'} = $6;
2780 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
2781 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
2782 } else {
2783 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
2786 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
2787 # combined diff (for merge commit)
2788 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
2789 $res{'nparents'} = length($1);
2790 $res{'from_mode'} = [ split(' ', $2) ];
2791 $res{'to_mode'} = pop @{$res{'from_mode'}};
2792 $res{'from_id'} = [ split(' ', $3) ];
2793 $res{'to_id'} = pop @{$res{'from_id'}};
2794 $res{'status'} = [ split('', $4) ];
2795 $res{'to_file'} = unquote($5);
2797 # 'c512b523472485aef4fff9e57b229d9d243c967f'
2798 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
2799 $res{'commit'} = $1;
2802 return wantarray ? %res : \%res;
2805 # wrapper: return parsed line of git-diff-tree "raw" output
2806 # (the argument might be raw line, or parsed info)
2807 sub parsed_difftree_line {
2808 my $line_or_ref = shift;
2810 if (ref($line_or_ref) eq "HASH") {
2811 # pre-parsed (or generated by hand)
2812 return $line_or_ref;
2813 } else {
2814 return parse_difftree_raw_line($line_or_ref);
2818 # parse line of git-ls-tree output
2819 sub parse_ls_tree_line {
2820 my $line = shift;
2821 my %opts = @_;
2822 my %res;
2824 if ($opts{'-l'}) {
2825 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
2826 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
2828 $res{'mode'} = $1;
2829 $res{'type'} = $2;
2830 $res{'hash'} = $3;
2831 $res{'size'} = $4;
2832 if ($opts{'-z'}) {
2833 $res{'name'} = $5;
2834 } else {
2835 $res{'name'} = unquote($5);
2837 } else {
2838 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2839 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
2841 $res{'mode'} = $1;
2842 $res{'type'} = $2;
2843 $res{'hash'} = $3;
2844 if ($opts{'-z'}) {
2845 $res{'name'} = $4;
2846 } else {
2847 $res{'name'} = unquote($4);
2851 return wantarray ? %res : \%res;
2854 # generates _two_ hashes, references to which are passed as 2 and 3 argument
2855 sub parse_from_to_diffinfo {
2856 my ($diffinfo, $from, $to, @parents) = @_;
2858 if ($diffinfo->{'nparents'}) {
2859 # combined diff
2860 $from->{'file'} = [];
2861 $from->{'href'} = [];
2862 fill_from_file_info($diffinfo, @parents)
2863 unless exists $diffinfo->{'from_file'};
2864 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2865 $from->{'file'}[$i] =
2866 defined $diffinfo->{'from_file'}[$i] ?
2867 $diffinfo->{'from_file'}[$i] :
2868 $diffinfo->{'to_file'};
2869 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
2870 $from->{'href'}[$i] = href(action=>"blob",
2871 hash_base=>$parents[$i],
2872 hash=>$diffinfo->{'from_id'}[$i],
2873 file_name=>$from->{'file'}[$i]);
2874 } else {
2875 $from->{'href'}[$i] = undef;
2878 } else {
2879 # ordinary (not combined) diff
2880 $from->{'file'} = $diffinfo->{'from_file'};
2881 if ($diffinfo->{'status'} ne "A") { # not new (added) file
2882 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
2883 hash=>$diffinfo->{'from_id'},
2884 file_name=>$from->{'file'});
2885 } else {
2886 delete $from->{'href'};
2890 $to->{'file'} = $diffinfo->{'to_file'};
2891 if (!is_deleted($diffinfo)) { # file exists in result
2892 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
2893 hash=>$diffinfo->{'to_id'},
2894 file_name=>$to->{'file'});
2895 } else {
2896 delete $to->{'href'};
2900 ## ......................................................................
2901 ## parse to array of hashes functions
2903 sub git_get_heads_list {
2904 my $limit = shift;
2905 my @headslist;
2907 open my $fd, '-|', git_cmd(), 'for-each-ref',
2908 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
2909 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
2910 'refs/heads'
2911 or return;
2912 while (my $line = <$fd>) {
2913 my %ref_item;
2915 chomp $line;
2916 my ($refinfo, $committerinfo) = split(/\0/, $line);
2917 my ($hash, $name, $title) = split(' ', $refinfo, 3);
2918 my ($committer, $epoch, $tz) =
2919 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
2920 $ref_item{'fullname'} = $name;
2921 $name =~ s!^refs/heads/!!;
2923 $ref_item{'name'} = $name;
2924 $ref_item{'id'} = $hash;
2925 $ref_item{'title'} = $title || '(no commit message)';
2926 $ref_item{'epoch'} = $epoch;
2927 if ($epoch) {
2928 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2929 } else {
2930 $ref_item{'age'} = "unknown";
2933 push @headslist, \%ref_item;
2935 close $fd;
2937 return wantarray ? @headslist : \@headslist;
2940 sub git_get_tags_list {
2941 my $limit = shift;
2942 my @tagslist;
2944 open my $fd, '-|', git_cmd(), 'for-each-ref',
2945 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
2946 '--format=%(objectname) %(objecttype) %(refname) '.
2947 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
2948 'refs/tags'
2949 or return;
2950 while (my $line = <$fd>) {
2951 my %ref_item;
2953 chomp $line;
2954 my ($refinfo, $creatorinfo) = split(/\0/, $line);
2955 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
2956 my ($creator, $epoch, $tz) =
2957 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
2958 $ref_item{'fullname'} = $name;
2959 $name =~ s!^refs/tags/!!;
2961 $ref_item{'type'} = $type;
2962 $ref_item{'id'} = $id;
2963 $ref_item{'name'} = $name;
2964 if ($type eq "tag") {
2965 $ref_item{'subject'} = $title;
2966 $ref_item{'reftype'} = $reftype;
2967 $ref_item{'refid'} = $refid;
2968 } else {
2969 $ref_item{'reftype'} = $type;
2970 $ref_item{'refid'} = $id;
2973 if ($type eq "tag" || $type eq "commit") {
2974 $ref_item{'epoch'} = $epoch;
2975 if ($epoch) {
2976 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
2977 } else {
2978 $ref_item{'age'} = "unknown";
2982 push @tagslist, \%ref_item;
2984 close $fd;
2986 return wantarray ? @tagslist : \@tagslist;
2989 ## ----------------------------------------------------------------------
2990 ## filesystem-related functions
2992 sub get_file_owner {
2993 my $path = shift;
2995 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
2996 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
2997 if (!defined $gcos) {
2998 return undef;
3000 my $owner = $gcos;
3001 $owner =~ s/[,;].*$//;
3002 return to_utf8($owner);
3005 # assume that file exists
3006 sub insert_file {
3007 my $filename = shift;
3009 open my $fd, '<', $filename;
3010 print map { to_utf8($_) } <$fd>;
3011 close $fd;
3014 ## ......................................................................
3015 ## mimetype related functions
3017 sub mimetype_guess_file {
3018 my $filename = shift;
3019 my $mimemap = shift;
3020 -r $mimemap or return undef;
3022 my %mimemap;
3023 open(my $mh, '<', $mimemap) or return undef;
3024 while (<$mh>) {
3025 next if m/^#/; # skip comments
3026 my ($mimetype, $exts) = split(/\t+/);
3027 if (defined $exts) {
3028 my @exts = split(/\s+/, $exts);
3029 foreach my $ext (@exts) {
3030 $mimemap{$ext} = $mimetype;
3034 close($mh);
3036 $filename =~ /\.([^.]*)$/;
3037 return $mimemap{$1};
3040 sub mimetype_guess {
3041 my $filename = shift;
3042 my $mime;
3043 $filename =~ /\./ or return undef;
3045 if ($mimetypes_file) {
3046 my $file = $mimetypes_file;
3047 if ($file !~ m!^/!) { # if it is relative path
3048 # it is relative to project
3049 $file = "$projectroot/$project/$file";
3051 $mime = mimetype_guess_file($filename, $file);
3053 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3054 return $mime;
3057 sub blob_mimetype {
3058 my $fd = shift;
3059 my $filename = shift;
3061 if ($filename) {
3062 my $mime = mimetype_guess($filename);
3063 $mime and return $mime;
3066 # just in case
3067 return $default_blob_plain_mimetype unless $fd;
3069 if (-T $fd) {
3070 return 'text/plain';
3071 } elsif (! $filename) {
3072 return 'application/octet-stream';
3073 } elsif ($filename =~ m/\.png$/i) {
3074 return 'image/png';
3075 } elsif ($filename =~ m/\.gif$/i) {
3076 return 'image/gif';
3077 } elsif ($filename =~ m/\.jpe?g$/i) {
3078 return 'image/jpeg';
3079 } else {
3080 return 'application/octet-stream';
3084 sub blob_contenttype {
3085 my ($fd, $file_name, $type) = @_;
3087 $type ||= blob_mimetype($fd, $file_name);
3088 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3089 $type .= "; charset=$default_text_plain_charset";
3092 return $type;
3095 ## ======================================================================
3096 ## functions printing HTML: header, footer, error page
3098 sub git_header_html {
3099 my $status = shift || "200 OK";
3100 my $expires = shift;
3102 my $title = "$site_name";
3103 if (defined $project) {
3104 $title .= " - " . to_utf8($project);
3105 if (defined $action) {
3106 $title .= "/$action";
3107 if (defined $file_name) {
3108 $title .= " - " . esc_path($file_name);
3109 if ($action eq "tree" && $file_name !~ m|/$|) {
3110 $title .= "/";
3115 my $content_type;
3116 # require explicit support from the UA if we are to send the page as
3117 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3118 # we have to do this because MSIE sometimes globs '*/*', pretending to
3119 # support xhtml+xml but choking when it gets what it asked for.
3120 if (defined $cgi->http('HTTP_ACCEPT') &&
3121 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3122 $cgi->Accept('application/xhtml+xml') != 0) {
3123 $content_type = 'application/xhtml+xml';
3124 } else {
3125 $content_type = 'text/html';
3127 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3128 -status=> $status, -expires => $expires);
3129 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3130 print <<EOF;
3131 <?xml version="1.0" encoding="utf-8"?>
3132 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3133 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3134 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3135 <!-- git core binaries version $git_version -->
3136 <head>
3137 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3138 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3139 <meta name="robots" content="index, nofollow"/>
3140 <title>$title</title>
3141 <script type="text/javascript">/* <![CDATA[ */
3142 function fixBlameLinks() {
3143 var allLinks = document.getElementsByTagName("a");
3144 for (var i = 0; i < allLinks.length; i++) {
3145 var link = allLinks.item(i);
3146 if (link.className == 'blamelink')
3147 link.href = link.href.replace("/blame/", "/blame_incremental/");
3150 /* ]]> */</script>
3152 # the stylesheet, favicon etc urls won't work correctly with path_info
3153 # unless we set the appropriate base URL
3154 if ($ENV{'PATH_INFO'}) {
3155 print "<base href=\"".esc_url($base_url)."\" />\n";
3157 # print out each stylesheet that exist, providing backwards capability
3158 # for those people who defined $stylesheet in a config file
3159 if (defined $stylesheet) {
3160 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3161 } else {
3162 foreach my $stylesheet (@stylesheets) {
3163 next unless $stylesheet;
3164 print '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'"/>'."\n";
3167 if (defined $project) {
3168 my %href_params = get_feed_info();
3169 if (!exists $href_params{'-title'}) {
3170 $href_params{'-title'} = 'log';
3173 foreach my $format qw(RSS Atom) {
3174 my $type = lc($format);
3175 my %link_attr = (
3176 '-rel' => 'alternate',
3177 '-title' => "$project - $href_params{'-title'} - $format feed",
3178 '-type' => "application/$type+xml"
3181 $href_params{'action'} = $type;
3182 $link_attr{'-href'} = href(%href_params);
3183 print "<link ".
3184 "rel=\"$link_attr{'-rel'}\" ".
3185 "title=\"$link_attr{'-title'}\" ".
3186 "href=\"$link_attr{'-href'}\" ".
3187 "type=\"$link_attr{'-type'}\" ".
3188 "/>\n";
3190 $href_params{'extra_options'} = '--no-merges';
3191 $link_attr{'-href'} = href(%href_params);
3192 $link_attr{'-title'} .= ' (no merges)';
3193 print "<link ".
3194 "rel=\"$link_attr{'-rel'}\" ".
3195 "title=\"$link_attr{'-title'}\" ".
3196 "href=\"$link_attr{'-href'}\" ".
3197 "type=\"$link_attr{'-type'}\" ".
3198 "/>\n";
3201 } else {
3202 printf('<link rel="alternate" title="%s projects list" '.
3203 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3204 $site_name, href(project=>undef, action=>"project_index"));
3205 printf('<link rel="alternate" title="%s projects feeds" '.
3206 'href="%s" type="text/x-opml" />'."\n",
3207 $site_name, href(project=>undef, action=>"opml"));
3209 if (defined $favicon) {
3210 print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
3213 if (defined $gitwebjs) {
3214 print qq(<script src="$gitwebjs" type="text/javascript"></script>\n);
3217 print "</head>\n";
3218 if (gitweb_check_feature('blame_incremental')) {
3219 print "<body onload=\"fixBlameLinks();\">\n";
3220 } else {
3221 print "<body>\n";
3224 if (-f $site_header) {
3225 insert_file($site_header);
3228 print "<div class=\"page_header\">\n" .
3229 $cgi->a({-href => esc_url($logo_url),
3230 -title => $logo_label},
3231 qq(<img src="$logo" width="72" height="27" alt="git" class="logo"/>));
3232 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3233 if (defined $project) {
3234 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3235 if (defined $action) {
3236 print " / $action";
3238 print "\n";
3240 print "</div>\n";
3242 my $have_search = gitweb_check_feature('search');
3243 if (defined $project && $have_search) {
3244 if (!defined $searchtext) {
3245 $searchtext = "";
3247 my $search_hash;
3248 if (defined $hash_base) {
3249 $search_hash = $hash_base;
3250 } elsif (defined $hash) {
3251 $search_hash = $hash;
3252 } else {
3253 $search_hash = "HEAD";
3255 my $action = $my_uri;
3256 my $use_pathinfo = gitweb_check_feature('pathinfo');
3257 if ($use_pathinfo) {
3258 $action .= "/".esc_url($project);
3260 print $cgi->startform(-method => "get", -action => $action) .
3261 "<div class=\"search\">\n" .
3262 (!$use_pathinfo &&
3263 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3264 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3265 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3266 $cgi->popup_menu(-name => 'st', -default => 'commit',
3267 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3268 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3269 " search:\n",
3270 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3271 "<span title=\"Extended regular expression\">" .
3272 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3273 -checked => $search_use_regexp) .
3274 "</span>" .
3275 "</div>" .
3276 $cgi->end_form() . "\n";
3280 sub git_footer_html {
3281 my $feed_class = 'rss_logo';
3283 print "<div class=\"page_footer\">\n";
3284 if (defined $project) {
3285 my $descr = git_get_project_description($project);
3286 if (defined $descr) {
3287 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3290 my %href_params = get_feed_info();
3291 if (!%href_params) {
3292 $feed_class .= ' generic';
3294 $href_params{'-title'} ||= 'log';
3296 foreach my $format qw(RSS Atom) {
3297 $href_params{'action'} = lc($format);
3298 print $cgi->a({-href => href(%href_params),
3299 -title => "$href_params{'-title'} $format feed",
3300 -class => $feed_class}, $format)."\n";
3303 } else {
3304 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3305 -class => $feed_class}, "OPML") . " ";
3306 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3307 -class => $feed_class}, "TXT") . "\n";
3309 print "</div>\n"; # class="page_footer"
3311 if (-f $site_footer) {
3312 insert_file($site_footer);
3315 print "</body>\n" .
3316 "</html>";
3319 # die_error(<http_status_code>, <error_message>)
3320 # Example: die_error(404, 'Hash not found')
3321 # By convention, use the following status codes (as defined in RFC 2616):
3322 # 400: Invalid or missing CGI parameters, or
3323 # requested object exists but has wrong type.
3324 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3325 # this server or project.
3326 # 404: Requested object/revision/project doesn't exist.
3327 # 500: The server isn't configured properly, or
3328 # an internal error occurred (e.g. failed assertions caused by bugs), or
3329 # an unknown error occurred (e.g. the git binary died unexpectedly).
3330 sub die_error {
3331 my $status = shift || 500;
3332 my $error = shift || "Internal server error";
3334 my %http_responses = (400 => '400 Bad Request',
3335 403 => '403 Forbidden',
3336 404 => '404 Not Found',
3337 500 => '500 Internal Server Error');
3338 git_header_html($http_responses{$status});
3339 print <<EOF;
3340 <div class="page_body">
3341 <br /><br />
3342 $status - $error
3343 <br />
3344 </div>
3346 git_footer_html();
3347 exit;
3350 ## ----------------------------------------------------------------------
3351 ## functions printing or outputting HTML: navigation
3353 sub git_print_page_nav {
3354 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
3355 $extra = '' if !defined $extra; # pager or formats
3357 my @navs = qw(summary shortlog log commit commitdiff tree);
3358 if ($suppress) {
3359 @navs = grep { $_ ne $suppress } @navs;
3362 my %arg = map { $_ => {action=>$_} } @navs;
3363 if (defined $head) {
3364 for (qw(commit commitdiff)) {
3365 $arg{$_}{'hash'} = $head;
3367 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
3368 for (qw(shortlog log)) {
3369 $arg{$_}{'hash'} = $head;
3374 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
3375 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
3377 my @actions = gitweb_get_feature('actions');
3378 my %repl = (
3379 '%' => '%',
3380 'n' => $project, # project name
3381 'f' => $git_dir, # project path within filesystem
3382 'h' => $treehead || '', # current hash ('h' parameter)
3383 'b' => $treebase || '', # hash base ('hb' parameter)
3385 while (@actions) {
3386 my ($label, $link, $pos) = splice(@actions,0,3);
3387 # insert
3388 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
3389 # munch munch
3390 $link =~ s/%([%nfhb])/$repl{$1}/g;
3391 $arg{$label}{'_href'} = $link;
3394 print "<div class=\"page_nav\">\n" .
3395 (join " | ",
3396 map { $_ eq $current ?
3397 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
3398 } @navs);
3399 print "<br/>\n$extra<br/>\n" .
3400 "</div>\n";
3403 sub format_paging_nav {
3404 my ($action, $hash, $head, $page, $has_next_link) = @_;
3405 my $paging_nav;
3408 if ($hash ne $head || $page) {
3409 $paging_nav .= $cgi->a({-href => href(action=>$action)}, "HEAD");
3410 } else {
3411 $paging_nav .= "HEAD";
3414 if ($page > 0) {
3415 $paging_nav .= " &sdot; " .
3416 $cgi->a({-href => href(-replay=>1, page=>$page-1),
3417 -accesskey => "p", -title => "Alt-p"}, "prev");
3418 } else {
3419 $paging_nav .= " &sdot; prev";
3422 if ($has_next_link) {
3423 $paging_nav .= " &sdot; " .
3424 $cgi->a({-href => href(-replay=>1, page=>$page+1),
3425 -accesskey => "n", -title => "Alt-n"}, "next");
3426 } else {
3427 $paging_nav .= " &sdot; next";
3430 return $paging_nav;
3433 ## ......................................................................
3434 ## functions printing or outputting HTML: div
3436 sub git_print_header_div {
3437 my ($action, $title, $hash, $hash_base) = @_;
3438 my %args = ();
3440 $args{'action'} = $action;
3441 $args{'hash'} = $hash if $hash;
3442 $args{'hash_base'} = $hash_base if $hash_base;
3444 print "<div class=\"header\">\n" .
3445 $cgi->a({-href => href(%args), -class => "title"},
3446 $title ? $title : $action) .
3447 "\n</div>\n";
3450 sub print_local_time {
3451 my %date = @_;
3452 if ($date{'hour_local'} < 6) {
3453 printf(" (<span class=\"atnight\">%02d:%02d</span> %s)",
3454 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3455 } else {
3456 printf(" (%02d:%02d %s)",
3457 $date{'hour_local'}, $date{'minute_local'}, $date{'tz_local'});
3461 # Outputs the author name and date in long form
3462 sub git_print_authorship {
3463 my $co = shift;
3464 my %opts = @_;
3465 my $tag = $opts{-tag} || 'div';
3466 my $author = $co->{'author_name'};
3468 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
3469 print "<$tag class=\"author_date\">" .
3470 format_search_author($author, "author", esc_html($author)) .
3471 " [$ad{'rfc2822'}";
3472 print_local_time(%ad) if ($opts{-localtime});
3473 print "]" . git_get_avatar($co->{'author_email'}, -pad_before => 1)
3474 . "</$tag>\n";
3477 # Outputs table rows containing the full author or committer information,
3478 # in the format expected for 'commit' view (& similia).
3479 # Parameters are a commit hash reference, followed by the list of people
3480 # to output information for. If the list is empty it defalts to both
3481 # author and committer.
3482 sub git_print_authorship_rows {
3483 my $co = shift;
3484 # too bad we can't use @people = @_ || ('author', 'committer')
3485 my @people = @_;
3486 @people = ('author', 'committer') unless @people;
3487 foreach my $who (@people) {
3488 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
3489 print "<tr><td>$who</td><td>" .
3490 format_search_author($co->{"${who}_name"}, $who,
3491 esc_html($co->{"${who}_name"})) . " " .
3492 format_search_author($co->{"${who}_email"}, $who,
3493 esc_html("<" . $co->{"${who}_email"} . ">")) .
3494 "</td><td rowspan=\"2\">" .
3495 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
3496 "</td></tr>\n" .
3497 "<tr>" .
3498 "<td></td><td> $wd{'rfc2822'}";
3499 print_local_time(%wd);
3500 print "</td>" .
3501 "</tr>\n";
3505 sub git_print_page_path {
3506 my $name = shift;
3507 my $type = shift;
3508 my $hb = shift;
3511 print "<div class=\"page_path\">";
3512 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
3513 -title => 'tree root'}, to_utf8("[$project]"));
3514 print " / ";
3515 if (defined $name) {
3516 my @dirname = split '/', $name;
3517 my $basename = pop @dirname;
3518 my $fullname = '';
3520 foreach my $dir (@dirname) {
3521 $fullname .= ($fullname ? '/' : '') . $dir;
3522 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
3523 hash_base=>$hb),
3524 -title => $fullname}, esc_path($dir));
3525 print " / ";
3527 if (defined $type && $type eq 'blob') {
3528 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
3529 hash_base=>$hb),
3530 -title => $name}, esc_path($basename));
3531 } elsif (defined $type && $type eq 'tree') {
3532 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
3533 hash_base=>$hb),
3534 -title => $name}, esc_path($basename));
3535 print " / ";
3536 } else {
3537 print esc_path($basename);
3540 print "<br/></div>\n";
3543 sub git_print_log {
3544 my $log = shift;
3545 my %opts = @_;
3547 if ($opts{'-remove_title'}) {
3548 # remove title, i.e. first line of log
3549 shift @$log;
3551 # remove leading empty lines
3552 while (defined $log->[0] && $log->[0] eq "") {
3553 shift @$log;
3556 # print log
3557 my $signoff = 0;
3558 my $empty = 0;
3559 foreach my $line (@$log) {
3560 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
3561 $signoff = 1;
3562 $empty = 0;
3563 if (! $opts{'-remove_signoff'}) {
3564 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
3565 next;
3566 } else {
3567 # remove signoff lines
3568 next;
3570 } else {
3571 $signoff = 0;
3574 # print only one empty line
3575 # do not print empty line after signoff
3576 if ($line eq "") {
3577 next if ($empty || $signoff);
3578 $empty = 1;
3579 } else {
3580 $empty = 0;
3583 print format_log_line_html($line) . "<br/>\n";
3586 if ($opts{'-final_empty_line'}) {
3587 # end with single empty line
3588 print "<br/>\n" unless $empty;
3592 # return link target (what link points to)
3593 sub git_get_link_target {
3594 my $hash = shift;
3595 my $link_target;
3597 # read link
3598 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
3599 or return;
3601 local $/ = undef;
3602 $link_target = <$fd>;
3604 close $fd
3605 or return;
3607 return $link_target;
3610 # given link target, and the directory (basedir) the link is in,
3611 # return target of link relative to top directory (top tree);
3612 # return undef if it is not possible (including absolute links).
3613 sub normalize_link_target {
3614 my ($link_target, $basedir) = @_;
3616 # absolute symlinks (beginning with '/') cannot be normalized
3617 return if (substr($link_target, 0, 1) eq '/');
3619 # normalize link target to path from top (root) tree (dir)
3620 my $path;
3621 if ($basedir) {
3622 $path = $basedir . '/' . $link_target;
3623 } else {
3624 # we are in top (root) tree (dir)
3625 $path = $link_target;
3628 # remove //, /./, and /../
3629 my @path_parts;
3630 foreach my $part (split('/', $path)) {
3631 # discard '.' and ''
3632 next if (!$part || $part eq '.');
3633 # handle '..'
3634 if ($part eq '..') {
3635 if (@path_parts) {
3636 pop @path_parts;
3637 } else {
3638 # link leads outside repository (outside top dir)
3639 return;
3641 } else {
3642 push @path_parts, $part;
3645 $path = join('/', @path_parts);
3647 return $path;
3650 # print tree entry (row of git_tree), but without encompassing <tr> element
3651 sub git_print_tree_entry {
3652 my ($t, $basedir, $hash_base, $have_blame) = @_;
3654 my %base_key = ();
3655 $base_key{'hash_base'} = $hash_base if defined $hash_base;
3657 # The format of a table row is: mode list link. Where mode is
3658 # the mode of the entry, list is the name of the entry, an href,
3659 # and link is the action links of the entry.
3661 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
3662 if (exists $t->{'size'}) {
3663 print "<td class=\"size\">$t->{'size'}</td>\n";
3665 if ($t->{'type'} eq "blob") {
3666 print "<td class=\"list\">" .
3667 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3668 file_name=>"$basedir$t->{'name'}", %base_key),
3669 -class => "list"}, esc_path($t->{'name'}));
3670 if (S_ISLNK(oct $t->{'mode'})) {
3671 my $link_target = git_get_link_target($t->{'hash'});
3672 if ($link_target) {
3673 my $norm_target = normalize_link_target($link_target, $basedir);
3674 if (defined $norm_target) {
3675 print " -> " .
3676 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
3677 file_name=>$norm_target),
3678 -title => $norm_target}, esc_path($link_target));
3679 } else {
3680 print " -> " . esc_path($link_target);
3684 print "</td>\n";
3685 print "<td class=\"link\">";
3686 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
3687 file_name=>"$basedir$t->{'name'}", %base_key)},
3688 "blob");
3689 if ($have_blame) {
3690 print " | " .
3691 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
3692 file_name=>"$basedir$t->{'name'}", %base_key), -class => "blamelink"},
3693 "blame");
3695 if (defined $hash_base) {
3696 print " | " .
3697 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3698 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
3699 "history");
3701 print " | " .
3702 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
3703 file_name=>"$basedir$t->{'name'}")},
3704 "raw");
3705 print "</td>\n";
3707 } elsif ($t->{'type'} eq "tree") {
3708 print "<td class=\"list\">";
3709 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3710 file_name=>"$basedir$t->{'name'}",
3711 %base_key)},
3712 esc_path($t->{'name'}));
3713 print "</td>\n";
3714 print "<td class=\"link\">";
3715 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
3716 file_name=>"$basedir$t->{'name'}",
3717 %base_key)},
3718 "tree");
3719 if (defined $hash_base) {
3720 print " | " .
3721 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
3722 file_name=>"$basedir$t->{'name'}")},
3723 "history");
3725 print "</td>\n";
3726 } else {
3727 # unknown object: we can only present history for it
3728 # (this includes 'commit' object, i.e. submodule support)
3729 print "<td class=\"list\">" .
3730 esc_path($t->{'name'}) .
3731 "</td>\n";
3732 print "<td class=\"link\">";
3733 if (defined $hash_base) {
3734 print $cgi->a({-href => href(action=>"history",
3735 hash_base=>$hash_base,
3736 file_name=>"$basedir$t->{'name'}")},
3737 "history");
3739 print "</td>\n";
3743 ## ......................................................................
3744 ## functions printing large fragments of HTML
3746 # get pre-image filenames for merge (combined) diff
3747 sub fill_from_file_info {
3748 my ($diff, @parents) = @_;
3750 $diff->{'from_file'} = [ ];
3751 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
3752 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3753 if ($diff->{'status'}[$i] eq 'R' ||
3754 $diff->{'status'}[$i] eq 'C') {
3755 $diff->{'from_file'}[$i] =
3756 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
3760 return $diff;
3763 # is current raw difftree line of file deletion
3764 sub is_deleted {
3765 my $diffinfo = shift;
3767 return $diffinfo->{'to_id'} eq ('0' x 40);
3770 # does patch correspond to [previous] difftree raw line
3771 # $diffinfo - hashref of parsed raw diff format
3772 # $patchinfo - hashref of parsed patch diff format
3773 # (the same keys as in $diffinfo)
3774 sub is_patch_split {
3775 my ($diffinfo, $patchinfo) = @_;
3777 return defined $diffinfo && defined $patchinfo
3778 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
3782 sub git_difftree_body {
3783 my ($difftree, $hash, @parents) = @_;
3784 my ($parent) = $parents[0];
3785 my $have_blame = gitweb_check_feature('blame');
3786 print "<div class=\"list_head\">\n";
3787 if ($#{$difftree} > 10) {
3788 print(($#{$difftree} + 1) . " files changed:\n");
3790 print "</div>\n";
3792 print "<table class=\"" .
3793 (@parents > 1 ? "combined " : "") .
3794 "diff_tree\">\n";
3796 # header only for combined diff in 'commitdiff' view
3797 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
3798 if ($has_header) {
3799 # table header
3800 print "<thead><tr>\n" .
3801 "<th></th><th></th>\n"; # filename, patchN link
3802 for (my $i = 0; $i < @parents; $i++) {
3803 my $par = $parents[$i];
3804 print "<th>" .
3805 $cgi->a({-href => href(action=>"commitdiff",
3806 hash=>$hash, hash_parent=>$par),
3807 -title => 'commitdiff to parent number ' .
3808 ($i+1) . ': ' . substr($par,0,7)},
3809 $i+1) .
3810 "&nbsp;</th>\n";
3812 print "</tr></thead>\n<tbody>\n";
3815 my $alternate = 1;
3816 my $patchno = 0;
3817 foreach my $line (@{$difftree}) {
3818 my $diff = parsed_difftree_line($line);
3820 if ($alternate) {
3821 print "<tr class=\"dark\">\n";
3822 } else {
3823 print "<tr class=\"light\">\n";
3825 $alternate ^= 1;
3827 if (exists $diff->{'nparents'}) { # combined diff
3829 fill_from_file_info($diff, @parents)
3830 unless exists $diff->{'from_file'};
3832 if (!is_deleted($diff)) {
3833 # file exists in the result (child) commit
3834 print "<td>" .
3835 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3836 file_name=>$diff->{'to_file'},
3837 hash_base=>$hash),
3838 -class => "list"}, esc_path($diff->{'to_file'})) .
3839 "</td>\n";
3840 } else {
3841 print "<td>" .
3842 esc_path($diff->{'to_file'}) .
3843 "</td>\n";
3846 if ($action eq 'commitdiff') {
3847 # link to patch
3848 $patchno++;
3849 print "<td class=\"link\">" .
3850 $cgi->a({-href => "#patch$patchno"}, "patch") .
3851 " | " .
3852 "</td>\n";
3855 my $has_history = 0;
3856 my $not_deleted = 0;
3857 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
3858 my $hash_parent = $parents[$i];
3859 my $from_hash = $diff->{'from_id'}[$i];
3860 my $from_path = $diff->{'from_file'}[$i];
3861 my $status = $diff->{'status'}[$i];
3863 $has_history ||= ($status ne 'A');
3864 $not_deleted ||= ($status ne 'D');
3866 if ($status eq 'A') {
3867 print "<td class=\"link\" align=\"right\"> | </td>\n";
3868 } elsif ($status eq 'D') {
3869 print "<td class=\"link\">" .
3870 $cgi->a({-href => href(action=>"blob",
3871 hash_base=>$hash,
3872 hash=>$from_hash,
3873 file_name=>$from_path)},
3874 "blob" . ($i+1)) .
3875 " | </td>\n";
3876 } else {
3877 if ($diff->{'to_id'} eq $from_hash) {
3878 print "<td class=\"link nochange\">";
3879 } else {
3880 print "<td class=\"link\">";
3882 print $cgi->a({-href => href(action=>"blobdiff",
3883 hash=>$diff->{'to_id'},
3884 hash_parent=>$from_hash,
3885 hash_base=>$hash,
3886 hash_parent_base=>$hash_parent,
3887 file_name=>$diff->{'to_file'},
3888 file_parent=>$from_path)},
3889 "diff" . ($i+1)) .
3890 " | </td>\n";
3894 print "<td class=\"link\">";
3895 if ($not_deleted) {
3896 print $cgi->a({-href => href(action=>"blob",
3897 hash=>$diff->{'to_id'},
3898 file_name=>$diff->{'to_file'},
3899 hash_base=>$hash)},
3900 "blob");
3901 print " | " if ($has_history);
3903 if ($has_history) {
3904 print $cgi->a({-href => href(action=>"history",
3905 file_name=>$diff->{'to_file'},
3906 hash_base=>$hash)},
3907 "history");
3909 print "</td>\n";
3911 print "</tr>\n";
3912 next; # instead of 'else' clause, to avoid extra indent
3914 # else ordinary diff
3916 my ($to_mode_oct, $to_mode_str, $to_file_type);
3917 my ($from_mode_oct, $from_mode_str, $from_file_type);
3918 if ($diff->{'to_mode'} ne ('0' x 6)) {
3919 $to_mode_oct = oct $diff->{'to_mode'};
3920 if (S_ISREG($to_mode_oct)) { # only for regular file
3921 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
3923 $to_file_type = file_type($diff->{'to_mode'});
3925 if ($diff->{'from_mode'} ne ('0' x 6)) {
3926 $from_mode_oct = oct $diff->{'from_mode'};
3927 if (S_ISREG($to_mode_oct)) { # only for regular file
3928 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
3930 $from_file_type = file_type($diff->{'from_mode'});
3933 if ($diff->{'status'} eq "A") { # created
3934 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
3935 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
3936 $mode_chng .= "]</span>";
3937 print "<td>";
3938 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3939 hash_base=>$hash, file_name=>$diff->{'file'}),
3940 -class => "list"}, esc_path($diff->{'file'}));
3941 print "</td>\n";
3942 print "<td>$mode_chng</td>\n";
3943 print "<td class=\"link\">";
3944 if ($action eq 'commitdiff') {
3945 # link to patch
3946 $patchno++;
3947 print $cgi->a({-href => "#patch$patchno"}, "patch");
3948 print " | ";
3950 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
3951 hash_base=>$hash, file_name=>$diff->{'file'})},
3952 "blob");
3953 print "</td>\n";
3955 } elsif ($diff->{'status'} eq "D") { # deleted
3956 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
3957 print "<td>";
3958 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3959 hash_base=>$parent, file_name=>$diff->{'file'}),
3960 -class => "list"}, esc_path($diff->{'file'}));
3961 print "</td>\n";
3962 print "<td>$mode_chng</td>\n";
3963 print "<td class=\"link\">";
3964 if ($action eq 'commitdiff') {
3965 # link to patch
3966 $patchno++;
3967 print $cgi->a({-href => "#patch$patchno"}, "patch");
3968 print " | ";
3970 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
3971 hash_base=>$parent, file_name=>$diff->{'file'})},
3972 "blob") . " | ";
3973 if ($have_blame) {
3974 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
3975 file_name=>$diff->{'file'}), -class => "blamelink"},
3976 "blame") . " | ";
3978 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
3979 file_name=>$diff->{'file'})},
3980 "history");
3981 print "</td>\n";
3983 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
3984 my $mode_chnge = "";
3985 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
3986 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
3987 if ($from_file_type ne $to_file_type) {
3988 $mode_chnge .= " from $from_file_type to $to_file_type";
3990 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
3991 if ($from_mode_str && $to_mode_str) {
3992 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
3993 } elsif ($to_mode_str) {
3994 $mode_chnge .= " mode: $to_mode_str";
3997 $mode_chnge .= "]</span>\n";
3999 print "<td>";
4000 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4001 hash_base=>$hash, file_name=>$diff->{'file'}),
4002 -class => "list"}, esc_path($diff->{'file'}));
4003 print "</td>\n";
4004 print "<td>$mode_chnge</td>\n";
4005 print "<td class=\"link\">";
4006 if ($action eq 'commitdiff') {
4007 # link to patch
4008 $patchno++;
4009 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4010 " | ";
4011 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4012 # "commit" view and modified file (not onlu mode changed)
4013 print $cgi->a({-href => href(action=>"blobdiff",
4014 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4015 hash_base=>$hash, hash_parent_base=>$parent,
4016 file_name=>$diff->{'file'})},
4017 "diff") .
4018 " | ";
4020 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4021 hash_base=>$hash, file_name=>$diff->{'file'})},
4022 "blob") . " | ";
4023 if ($have_blame) {
4024 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4025 file_name=>$diff->{'file'}), -class => "blamelink"},
4026 "blame") . " | ";
4028 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4029 file_name=>$diff->{'file'})},
4030 "history");
4031 print "</td>\n";
4033 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4034 my %status_name = ('R' => 'moved', 'C' => 'copied');
4035 my $nstatus = $status_name{$diff->{'status'}};
4036 my $mode_chng = "";
4037 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4038 # mode also for directories, so we cannot use $to_mode_str
4039 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4041 print "<td>" .
4042 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4043 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4044 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4045 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4046 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4047 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4048 -class => "list"}, esc_path($diff->{'from_file'})) .
4049 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4050 "<td class=\"link\">";
4051 if ($action eq 'commitdiff') {
4052 # link to patch
4053 $patchno++;
4054 print $cgi->a({-href => "#patch$patchno"}, "patch") .
4055 " | ";
4056 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4057 # "commit" view and modified file (not only pure rename or copy)
4058 print $cgi->a({-href => href(action=>"blobdiff",
4059 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4060 hash_base=>$hash, hash_parent_base=>$parent,
4061 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4062 "diff") .
4063 " | ";
4065 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4066 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4067 "blob") . " | ";
4068 if ($have_blame) {
4069 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4070 file_name=>$diff->{'to_file'}), -class => "blamelink"},
4071 "blame") . " | ";
4073 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4074 file_name=>$diff->{'to_file'})},
4075 "history");
4076 print "</td>\n";
4078 } # we should not encounter Unmerged (U) or Unknown (X) status
4079 print "</tr>\n";
4081 print "</tbody>" if $has_header;
4082 print "</table>\n";
4085 sub git_patchset_body {
4086 my ($fd, $difftree, $hash, @hash_parents) = @_;
4087 my ($hash_parent) = $hash_parents[0];
4089 my $is_combined = (@hash_parents > 1);
4090 my $patch_idx = 0;
4091 my $patch_number = 0;
4092 my $patch_line;
4093 my $diffinfo;
4094 my $to_name;
4095 my (%from, %to);
4097 print "<div class=\"patchset\">\n";
4099 # skip to first patch
4100 while ($patch_line = <$fd>) {
4101 chomp $patch_line;
4103 last if ($patch_line =~ m/^diff /);
4106 PATCH:
4107 while ($patch_line) {
4109 # parse "git diff" header line
4110 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4111 # $1 is from_name, which we do not use
4112 $to_name = unquote($2);
4113 $to_name =~ s!^b/!!;
4114 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4115 # $1 is 'cc' or 'combined', which we do not use
4116 $to_name = unquote($2);
4117 } else {
4118 $to_name = undef;
4121 # check if current patch belong to current raw line
4122 # and parse raw git-diff line if needed
4123 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4124 # this is continuation of a split patch
4125 print "<div class=\"patch cont\">\n";
4126 } else {
4127 # advance raw git-diff output if needed
4128 $patch_idx++ if defined $diffinfo;
4130 # read and prepare patch information
4131 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4133 # compact combined diff output can have some patches skipped
4134 # find which patch (using pathname of result) we are at now;
4135 if ($is_combined) {
4136 while ($to_name ne $diffinfo->{'to_file'}) {
4137 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4138 format_diff_cc_simplified($diffinfo, @hash_parents) .
4139 "</div>\n"; # class="patch"
4141 $patch_idx++;
4142 $patch_number++;
4144 last if $patch_idx > $#$difftree;
4145 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4149 # modifies %from, %to hashes
4150 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4152 # this is first patch for raw difftree line with $patch_idx index
4153 # we index @$difftree array from 0, but number patches from 1
4154 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4157 # git diff header
4158 #assert($patch_line =~ m/^diff /) if DEBUG;
4159 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4160 $patch_number++;
4161 # print "git diff" header
4162 print format_git_diff_header_line($patch_line, $diffinfo,
4163 \%from, \%to);
4165 # print extended diff header
4166 print "<div class=\"diff extended_header\">\n";
4167 EXTENDED_HEADER:
4168 while ($patch_line = <$fd>) {
4169 chomp $patch_line;
4171 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4173 print format_extended_diff_header_line($patch_line, $diffinfo,
4174 \%from, \%to);
4176 print "</div>\n"; # class="diff extended_header"
4178 # from-file/to-file diff header
4179 if (! $patch_line) {
4180 print "</div>\n"; # class="patch"
4181 last PATCH;
4183 next PATCH if ($patch_line =~ m/^diff /);
4184 #assert($patch_line =~ m/^---/) if DEBUG;
4186 my $last_patch_line = $patch_line;
4187 $patch_line = <$fd>;
4188 chomp $patch_line;
4189 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4191 print format_diff_from_to_header($last_patch_line, $patch_line,
4192 $diffinfo, \%from, \%to,
4193 @hash_parents);
4195 # the patch itself
4196 LINE:
4197 while ($patch_line = <$fd>) {
4198 chomp $patch_line;
4200 next PATCH if ($patch_line =~ m/^diff /);
4202 print format_diff_line($patch_line, \%from, \%to);
4205 } continue {
4206 print "</div>\n"; # class="patch"
4209 # for compact combined (--cc) format, with chunk and patch simpliciaction
4210 # patchset might be empty, but there might be unprocessed raw lines
4211 for (++$patch_idx if $patch_number > 0;
4212 $patch_idx < @$difftree;
4213 ++$patch_idx) {
4214 # read and prepare patch information
4215 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4217 # generate anchor for "patch" links in difftree / whatchanged part
4218 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4219 format_diff_cc_simplified($diffinfo, @hash_parents) .
4220 "</div>\n"; # class="patch"
4222 $patch_number++;
4225 if ($patch_number == 0) {
4226 if (@hash_parents > 1) {
4227 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4228 } else {
4229 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4233 print "</div>\n"; # class="patchset"
4236 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4238 # fills project list info (age, description, owner, forks) for each
4239 # project in the list, removing invalid projects from returned list
4240 # NOTE: modifies $projlist, but does not remove entries from it
4241 sub fill_project_list_info {
4242 my ($projlist, $check_forks) = @_;
4243 my @projects;
4245 my $show_ctags = gitweb_check_feature('ctags');
4246 PROJECT:
4247 foreach my $pr (@$projlist) {
4248 my (@activity) = git_get_last_activity($pr->{'path'});
4249 unless (@activity) {
4250 next PROJECT;
4252 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4253 if (!defined $pr->{'descr'}) {
4254 my $descr = git_get_project_description($pr->{'path'}) || "";
4255 $descr = to_utf8($descr);
4256 $pr->{'descr_long'} = $descr;
4257 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4259 if (!defined $pr->{'owner'}) {
4260 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4262 if ($check_forks) {
4263 my $pname = $pr->{'path'};
4264 if (($pname =~ s/\.git$//) &&
4265 ($pname !~ /\/$/) &&
4266 (-d "$projectroot/$pname")) {
4267 $pr->{'forks'} = "-d $projectroot/$pname";
4268 } else {
4269 $pr->{'forks'} = 0;
4272 $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4273 push @projects, $pr;
4276 return @projects;
4279 # print 'sort by' <th> element, generating 'sort by $name' replay link
4280 # if that order is not selected
4281 sub print_sort_th {
4282 my ($name, $order, $header) = @_;
4283 $header ||= ucfirst($name);
4285 if ($order eq $name) {
4286 print "<th>$header</th>\n";
4287 } else {
4288 print "<th>" .
4289 $cgi->a({-href => href(-replay=>1, order=>$name),
4290 -class => "header"}, $header) .
4291 "</th>\n";
4295 sub git_project_list_body {
4296 # actually uses global variable $project
4297 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
4299 my $check_forks = gitweb_check_feature('forks');
4300 my @projects = fill_project_list_info($projlist, $check_forks);
4302 $order ||= $default_projects_order;
4303 $from = 0 unless defined $from;
4304 $to = $#projects if (!defined $to || $#projects < $to);
4306 my %order_info = (
4307 project => { key => 'path', type => 'str' },
4308 descr => { key => 'descr_long', type => 'str' },
4309 owner => { key => 'owner', type => 'str' },
4310 age => { key => 'age', type => 'num' }
4312 my $oi = $order_info{$order};
4313 if ($oi->{'type'} eq 'str') {
4314 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects;
4315 } else {
4316 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects;
4319 my $show_ctags = gitweb_check_feature('ctags');
4320 if ($show_ctags) {
4321 my %ctags;
4322 foreach my $p (@projects) {
4323 foreach my $ct (keys %{$p->{'ctags'}}) {
4324 $ctags{$ct} += $p->{'ctags'}->{$ct};
4327 my $cloud = git_populate_project_tagcloud(\%ctags);
4328 print git_show_project_tagcloud($cloud, 64);
4331 print "<table class=\"project_list\">\n";
4332 unless ($no_header) {
4333 print "<tr>\n";
4334 if ($check_forks) {
4335 print "<th></th>\n";
4337 print_sort_th('project', $order, 'Project');
4338 print_sort_th('descr', $order, 'Description');
4339 print_sort_th('owner', $order, 'Owner');
4340 print_sort_th('age', $order, 'Last Change');
4341 print "<th></th>\n" . # for links
4342 "</tr>\n";
4344 my $alternate = 1;
4345 my $tagfilter = $cgi->param('by_tag');
4346 for (my $i = $from; $i <= $to; $i++) {
4347 my $pr = $projects[$i];
4349 next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}};
4350 next if $searchtext and not $pr->{'path'} =~ /$searchtext/
4351 and not $pr->{'descr_long'} =~ /$searchtext/;
4352 # Weed out forks or non-matching entries of search
4353 if ($check_forks) {
4354 my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#;
4355 $forkbase="^$forkbase" if $forkbase;
4356 next if not $searchtext and not $tagfilter and $show_ctags
4357 and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe
4360 if ($alternate) {
4361 print "<tr class=\"dark\">\n";
4362 } else {
4363 print "<tr class=\"light\">\n";
4365 $alternate ^= 1;
4366 if ($check_forks) {
4367 print "<td>";
4368 if ($pr->{'forks'}) {
4369 print "<!-- $pr->{'forks'} -->\n";
4370 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "+");
4372 print "</td>\n";
4374 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4375 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
4376 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
4377 -class => "list", -title => $pr->{'descr_long'}},
4378 esc_html($pr->{'descr'})) . "</td>\n" .
4379 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
4380 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
4381 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
4382 "<td class=\"link\">" .
4383 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
4384 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
4385 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
4386 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
4387 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
4388 "</td>\n" .
4389 "</tr>\n";
4391 if (defined $extra) {
4392 print "<tr>\n";
4393 if ($check_forks) {
4394 print "<td></td>\n";
4396 print "<td colspan=\"5\">$extra</td>\n" .
4397 "</tr>\n";
4399 print "</table>\n";
4402 sub git_shortlog_body {
4403 # uses global variable $project
4404 my ($commitlist, $from, $to, $refs, $extra) = @_;
4406 $from = 0 unless defined $from;
4407 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4409 print "<table class=\"shortlog\">\n";
4410 my $alternate = 1;
4411 for (my $i = $from; $i <= $to; $i++) {
4412 my %co = %{$commitlist->[$i]};
4413 my $commit = $co{'id'};
4414 my $ref = format_ref_marker($refs, $commit);
4415 if ($alternate) {
4416 print "<tr class=\"dark\">\n";
4417 } else {
4418 print "<tr class=\"light\">\n";
4420 $alternate ^= 1;
4421 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
4422 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4423 format_author_html('td', \%co, 10) . "<td>";
4424 print format_subject_html($co{'title'}, $co{'title_short'},
4425 href(action=>"commit", hash=>$commit), $ref);
4426 print "</td>\n" .
4427 "<td class=\"link\">" .
4428 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
4429 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
4430 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
4431 my $snapshot_links = format_snapshot_links($commit);
4432 if (defined $snapshot_links) {
4433 print " | " . $snapshot_links;
4435 print "</td>\n" .
4436 "</tr>\n";
4438 if (defined $extra) {
4439 print "<tr>\n" .
4440 "<td colspan=\"4\">$extra</td>\n" .
4441 "</tr>\n";
4443 print "</table>\n";
4446 sub git_history_body {
4447 # Warning: assumes constant type (blob or tree) during history
4448 my ($commitlist, $from, $to, $refs, $hash_base, $ftype, $extra) = @_;
4450 $from = 0 unless defined $from;
4451 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
4453 print "<table class=\"history\">\n";
4454 my $alternate = 1;
4455 for (my $i = $from; $i <= $to; $i++) {
4456 my %co = %{$commitlist->[$i]};
4457 if (!%co) {
4458 next;
4460 my $commit = $co{'id'};
4462 my $ref = format_ref_marker($refs, $commit);
4464 if ($alternate) {
4465 print "<tr class=\"dark\">\n";
4466 } else {
4467 print "<tr class=\"light\">\n";
4469 $alternate ^= 1;
4470 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4471 # shortlog: format_author_html('td', \%co, 10)
4472 format_author_html('td', \%co, 15, 3) . "<td>";
4473 # originally git_history used chop_str($co{'title'}, 50)
4474 print format_subject_html($co{'title'}, $co{'title_short'},
4475 href(action=>"commit", hash=>$commit), $ref);
4476 print "</td>\n" .
4477 "<td class=\"link\">" .
4478 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
4479 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
4481 if ($ftype eq 'blob') {
4482 my $blob_current = git_get_hash_by_path($hash_base, $file_name);
4483 my $blob_parent = git_get_hash_by_path($commit, $file_name);
4484 if (defined $blob_current && defined $blob_parent &&
4485 $blob_current ne $blob_parent) {
4486 print " | " .
4487 $cgi->a({-href => href(action=>"blobdiff",
4488 hash=>$blob_current, hash_parent=>$blob_parent,
4489 hash_base=>$hash_base, hash_parent_base=>$commit,
4490 file_name=>$file_name)},
4491 "diff to current");
4494 print "</td>\n" .
4495 "</tr>\n";
4497 if (defined $extra) {
4498 print "<tr>\n" .
4499 "<td colspan=\"4\">$extra</td>\n" .
4500 "</tr>\n";
4502 print "</table>\n";
4505 sub git_tags_body {
4506 # uses global variable $project
4507 my ($taglist, $from, $to, $extra) = @_;
4508 $from = 0 unless defined $from;
4509 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
4511 print "<table class=\"tags\">\n";
4512 my $alternate = 1;
4513 for (my $i = $from; $i <= $to; $i++) {
4514 my $entry = $taglist->[$i];
4515 my %tag = %$entry;
4516 my $comment = $tag{'subject'};
4517 my $comment_short;
4518 if (defined $comment) {
4519 $comment_short = chop_str($comment, 30, 5);
4521 if ($alternate) {
4522 print "<tr class=\"dark\">\n";
4523 } else {
4524 print "<tr class=\"light\">\n";
4526 $alternate ^= 1;
4527 if (defined $tag{'age'}) {
4528 print "<td><i>$tag{'age'}</i></td>\n";
4529 } else {
4530 print "<td></td>\n";
4532 print "<td>" .
4533 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
4534 -class => "list name"}, esc_html($tag{'name'})) .
4535 "</td>\n" .
4536 "<td>";
4537 if (defined $comment) {
4538 print format_subject_html($comment, $comment_short,
4539 href(action=>"tag", hash=>$tag{'id'}));
4541 print "</td>\n" .
4542 "<td class=\"selflink\">";
4543 if ($tag{'type'} eq "tag") {
4544 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
4545 } else {
4546 print "&nbsp;";
4548 print "</td>\n" .
4549 "<td class=\"link\">" . " | " .
4550 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
4551 if ($tag{'reftype'} eq "commit") {
4552 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
4553 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
4554 } elsif ($tag{'reftype'} eq "blob") {
4555 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
4557 print "</td>\n" .
4558 "</tr>";
4560 if (defined $extra) {
4561 print "<tr>\n" .
4562 "<td colspan=\"5\">$extra</td>\n" .
4563 "</tr>\n";
4565 print "</table>\n";
4568 sub git_heads_body {
4569 # uses global variable $project
4570 my ($headlist, $head, $from, $to, $extra) = @_;
4571 $from = 0 unless defined $from;
4572 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
4574 print "<table class=\"heads\">\n";
4575 my $alternate = 1;
4576 for (my $i = $from; $i <= $to; $i++) {
4577 my $entry = $headlist->[$i];
4578 my %ref = %$entry;
4579 my $curr = $ref{'id'} eq $head;
4580 if ($alternate) {
4581 print "<tr class=\"dark\">\n";
4582 } else {
4583 print "<tr class=\"light\">\n";
4585 $alternate ^= 1;
4586 print "<td><i>$ref{'age'}</i></td>\n" .
4587 ($curr ? "<td class=\"current_head\">" : "<td>") .
4588 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
4589 -class => "list name"},esc_html($ref{'name'})) .
4590 "</td>\n" .
4591 "<td class=\"link\">" .
4592 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
4593 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
4594 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
4595 "</td>\n" .
4596 "</tr>";
4598 if (defined $extra) {
4599 print "<tr>\n" .
4600 "<td colspan=\"3\">$extra</td>\n" .
4601 "</tr>\n";
4603 print "</table>\n";
4606 sub git_search_grep_body {
4607 my ($commitlist, $from, $to, $extra) = @_;
4608 $from = 0 unless defined $from;
4609 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
4611 print "<table class=\"commit_search\">\n";
4612 my $alternate = 1;
4613 for (my $i = $from; $i <= $to; $i++) {
4614 my %co = %{$commitlist->[$i]};
4615 if (!%co) {
4616 next;
4618 my $commit = $co{'id'};
4619 if ($alternate) {
4620 print "<tr class=\"dark\">\n";
4621 } else {
4622 print "<tr class=\"light\">\n";
4624 $alternate ^= 1;
4625 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
4626 format_author_html('td', \%co, 15, 5) .
4627 "<td>" .
4628 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
4629 -class => "list subject"},
4630 chop_and_escape_str($co{'title'}, 50) . "<br/>");
4631 my $comment = $co{'comment'};
4632 foreach my $line (@$comment) {
4633 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
4634 my ($lead, $match, $trail) = ($1, $2, $3);
4635 $match = chop_str($match, 70, 5, 'center');
4636 my $contextlen = int((80 - length($match))/2);
4637 $contextlen = 30 if ($contextlen > 30);
4638 $lead = chop_str($lead, $contextlen, 10, 'left');
4639 $trail = chop_str($trail, $contextlen, 10, 'right');
4641 $lead = esc_html($lead);
4642 $match = esc_html($match);
4643 $trail = esc_html($trail);
4645 print "$lead<span class=\"match\">$match</span>$trail<br />";
4648 print "</td>\n" .
4649 "<td class=\"link\">" .
4650 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
4651 " | " .
4652 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
4653 " | " .
4654 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
4655 print "</td>\n" .
4656 "</tr>\n";
4658 if (defined $extra) {
4659 print "<tr>\n" .
4660 "<td colspan=\"3\">$extra</td>\n" .
4661 "</tr>\n";
4663 print "</table>\n";
4666 ## ======================================================================
4667 ## ======================================================================
4668 ## actions
4670 sub git_project_list {
4671 my $order = $input_params{'order'};
4672 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4673 die_error(400, "Unknown order parameter");
4676 my @list = git_get_projects_list();
4677 if (!@list) {
4678 die_error(404, "No projects found");
4681 git_header_html();
4682 if (-f $home_text) {
4683 print "<div class=\"index_include\">\n";
4684 insert_file($home_text);
4685 print "</div>\n";
4687 print $cgi->startform(-method => "get") .
4688 "<p class=\"projsearch\">Search:\n" .
4689 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
4690 "</p>" .
4691 $cgi->end_form() . "\n";
4692 git_project_list_body(\@list, $order);
4693 git_footer_html();
4696 sub git_forks {
4697 my $order = $input_params{'order'};
4698 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
4699 die_error(400, "Unknown order parameter");
4702 my @list = git_get_projects_list($project);
4703 if (!@list) {
4704 die_error(404, "No forks found");
4707 git_header_html();
4708 git_print_page_nav('','');
4709 git_print_header_div('summary', "$project forks");
4710 git_project_list_body(\@list, $order);
4711 git_footer_html();
4714 sub git_project_index {
4715 my @projects = git_get_projects_list($project);
4717 print $cgi->header(
4718 -type => 'text/plain',
4719 -charset => 'utf-8',
4720 -content_disposition => 'inline; filename="index.aux"');
4722 foreach my $pr (@projects) {
4723 if (!exists $pr->{'owner'}) {
4724 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
4727 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
4728 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
4729 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4730 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
4731 $path =~ s/ /\+/g;
4732 $owner =~ s/ /\+/g;
4734 print "$path $owner\n";
4738 sub git_summary {
4739 my $descr = git_get_project_description($project) || "none";
4740 my %co = parse_commit("HEAD");
4741 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
4742 my $head = $co{'id'};
4744 my $owner = git_get_project_owner($project);
4746 my $refs = git_get_references();
4747 # These get_*_list functions return one more to allow us to see if
4748 # there are more ...
4749 my @taglist = git_get_tags_list(16);
4750 my @headlist = git_get_heads_list(16);
4751 my @forklist;
4752 my $check_forks = gitweb_check_feature('forks');
4754 if ($check_forks) {
4755 @forklist = git_get_projects_list($project);
4758 git_header_html();
4759 git_print_page_nav('summary','', $head);
4761 print "<div class=\"title\">&nbsp;</div>\n";
4762 print "<table class=\"projects_list\">\n" .
4763 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
4764 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
4765 if (defined $cd{'rfc2822'}) {
4766 print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n";
4769 # use per project git URL list in $projectroot/$project/cloneurl
4770 # or make project git URL from git base URL and project name
4771 my $url_tag = "URL";
4772 my @url_list = git_get_project_url_list($project);
4773 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
4774 foreach my $git_url (@url_list) {
4775 next unless $git_url;
4776 print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n";
4777 $url_tag = "";
4780 # Tag cloud
4781 my $show_ctags = gitweb_check_feature('ctags');
4782 if ($show_ctags) {
4783 my $ctags = git_get_project_ctags($project);
4784 my $cloud = git_populate_project_tagcloud($ctags);
4785 print "<tr id=\"metadata_ctags\"><td>Content tags:<br />";
4786 print "</td>\n<td>" unless %$ctags;
4787 print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>";
4788 print "</td>\n<td>" if %$ctags;
4789 print git_show_project_tagcloud($cloud, 48);
4790 print "</td></tr>";
4793 print "</table>\n";
4795 # If XSS prevention is on, we don't include README.html.
4796 # TODO: Allow a readme in some safe format.
4797 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
4798 print "<div class=\"title\">readme</div>\n" .
4799 "<div class=\"readme\">\n";
4800 insert_file("$projectroot/$project/README.html");
4801 print "\n</div>\n"; # class="readme"
4804 # we need to request one more than 16 (0..15) to check if
4805 # those 16 are all
4806 my @commitlist = $head ? parse_commits($head, 17) : ();
4807 if (@commitlist) {
4808 git_print_header_div('shortlog');
4809 git_shortlog_body(\@commitlist, 0, 15, $refs,
4810 $#commitlist <= 15 ? undef :
4811 $cgi->a({-href => href(action=>"shortlog")}, "..."));
4814 if (@taglist) {
4815 git_print_header_div('tags');
4816 git_tags_body(\@taglist, 0, 15,
4817 $#taglist <= 15 ? undef :
4818 $cgi->a({-href => href(action=>"tags")}, "..."));
4821 if (@headlist) {
4822 git_print_header_div('heads');
4823 git_heads_body(\@headlist, $head, 0, 15,
4824 $#headlist <= 15 ? undef :
4825 $cgi->a({-href => href(action=>"heads")}, "..."));
4828 if (@forklist) {
4829 git_print_header_div('forks');
4830 git_project_list_body(\@forklist, 'age', 0, 15,
4831 $#forklist <= 15 ? undef :
4832 $cgi->a({-href => href(action=>"forks")}, "..."),
4833 'no_header');
4836 git_footer_html();
4839 sub git_tag {
4840 my $head = git_get_head_hash($project);
4841 git_header_html();
4842 git_print_page_nav('','', $head,undef,$head);
4843 my %tag = parse_tag($hash);
4845 if (! %tag) {
4846 die_error(404, "Unknown tag object");
4849 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
4850 print "<div class=\"title_text\">\n" .
4851 "<table class=\"object_header\">\n" .
4852 "<tr>\n" .
4853 "<td>object</td>\n" .
4854 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4855 $tag{'object'}) . "</td>\n" .
4856 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
4857 $tag{'type'}) . "</td>\n" .
4858 "</tr>\n";
4859 if (defined($tag{'author'})) {
4860 git_print_authorship_rows(\%tag, 'author');
4862 print "</table>\n\n" .
4863 "</div>\n";
4864 print "<div class=\"page_body\">";
4865 my $comment = $tag{'comment'};
4866 foreach my $line (@$comment) {
4867 chomp $line;
4868 print esc_html($line, -nbsp=>1) . "<br/>\n";
4870 print "</div>\n";
4871 git_footer_html();
4874 sub git_blame_data {
4875 my $ftype;
4877 my ($have_blame) = gitweb_check_feature('blame');
4878 if (!$have_blame) {
4879 die_error('403 Permission denied', "Permission denied");
4881 die_error('404 Not Found', "File name not defined") if (!$file_name);
4882 $hash_base ||= git_get_head_hash($project);
4883 die_error(undef, "Couldn't find base commit") unless ($hash_base);
4884 my %co = parse_commit($hash_base)
4885 or die_error(undef, "Reading commit failed");
4886 if (!defined $hash) {
4887 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4888 or die_error(undef, "Error looking up file");
4890 $ftype = git_get_type($hash);
4891 if ($ftype !~ "blob") {
4892 die_error("400 Bad Request", "Object is not a blob");
4894 open my $fd, "-|", git_cmd(), "blame", '--incremental',
4895 $hash_base, '--', $file_name
4896 or die_error(undef, "Open git-blame --incremental failed");
4898 print $cgi->header(-type=>"text/plain", -charset => 'utf-8',
4899 -status=> "200 OK");
4901 while(<$fd>) {
4902 if (/^([0-9a-f]{40}) ([0-9]+) ([0-9]+) ([0-9]+)/ or
4903 /^author-time |^author |^filename /) {
4904 print;
4908 close $fd or print "Reading blame data failed\n";
4911 sub git_blame_common {
4912 my ($type) = @_;
4914 # permissions
4915 gitweb_check_feature('blame')
4916 or die_error(403, "Blame view not allowed");
4918 # error checking
4919 die_error(400, "No file name given") unless $file_name;
4920 $hash_base ||= git_get_head_hash($project);
4921 die_error(404, "Couldn't find base commit") unless $hash_base;
4922 my %co = parse_commit($hash_base)
4923 or die_error(404, "Commit not found");
4924 my $ftype = "blob";
4925 if (!defined $hash) {
4926 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
4927 or die_error(404, "Error looking up file");
4928 } else {
4929 $ftype = git_get_type($hash);
4930 if ($ftype !~ "blob") {
4931 die_error(400, "Object is not a blob");
4934 $ftype = git_get_type($hash);
4935 if ($ftype !~ "blob") {
4936 die_error(400, "Object is not a blob");
4938 my $fd;
4939 if ($type eq 'incremental') {
4940 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
4941 or die_error(undef, "Open git-cat-file failed");
4942 } else {
4943 # run git-blame --porcelain
4944 open $fd, "-|", git_cmd(), "blame", '-p',
4945 $hash_base, '--', $file_name
4946 or die_error(500, "Open git-blame failed");
4949 # page header
4950 git_header_html();
4951 my $formats_nav =
4952 $cgi->a({-href => href(action=>"blob", -replay=>1)},
4953 "blob") .
4954 " | " .
4955 $cgi->a({-href => href(action=>"history", -replay=>1)},
4956 "history") .
4957 " | " .
4958 $cgi->a({-href => href(action=>"blame", file_name=>$file_name), -class => "blamelink"},
4959 "HEAD");
4960 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
4961 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
4962 git_print_page_path($file_name, $ftype, $hash_base);
4964 # page body
4965 my @rev_color = qw(light dark);
4966 my $num_colors = scalar(@rev_color);
4967 my $current_color = 0;
4968 my %metainfo = ();
4970 print <<HTML;
4972 <div class="page_body">
4973 <table class="blame">
4974 <tr><th>Commit&nbsp;<a href="javascript:extra_blame_columns()" id="columns_expander">[+]</a></th>
4975 <th class="extra_column">Author</th>
4976 <th class="extra_column">Date</th>
4977 <th>Line</th>
4978 <th>Data</th></tr>
4979 HTML
4980 LINE:
4981 my $linenr = 0;
4982 while (my $line = <$fd>) {
4983 chomp $line;
4984 if ($type eq 'incremental') {
4985 # Empty stage with just the file contents
4986 $linenr += 1;
4987 print "<tr id=\"l$linenr\" class=\"light2\">";
4988 print '<td class="sha1"><a href=""></a></td>';
4989 print "<td class=\"extra_column\"></td>";
4990 print "<td class=\"extra_column\"></td>";
4991 print "<td class=\"linenr\"><a class=\"linenr\" href=\"\">$linenr</a></td><td class=\"pre\">" . esc_html($line) . "</td>\n";
4992 print "</tr>\n";
4993 next;
4996 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
4997 # no <lines in group> for subsequent lines in group of lines
4998 my ($full_rev, $orig_lineno, $lineno, $group_size) =
4999 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
5000 if (!exists $metainfo{$full_rev}) {
5001 $metainfo{$full_rev} = { 'nprevious' => 0 };
5003 my $meta = $metainfo{$full_rev};
5004 my $data;
5005 while ($data = <$fd>) {
5006 chomp $data;
5007 last if ($data =~ s/^\t//); # contents of line
5008 if ($data =~ /^(\S+)(?: (.*))?$/) {
5009 $meta->{$1} = $2 unless exists $meta->{$1};
5011 if ($data =~ /^previous /) {
5012 $meta->{'nprevious'}++;
5015 my $short_rev = substr($full_rev, 0, 8);
5016 my $author = $meta->{'author'};
5017 my %date =
5018 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
5019 my $date = $date{'iso-tz'};
5020 if ($group_size) {
5021 $current_color = ($current_color + 1) % $num_colors;
5023 my $tr_class = $rev_color[$current_color];
5024 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
5025 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
5026 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
5027 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
5028 if ($group_size) {
5029 my $rowspan = $group_size > 1 ? " rowspan=\"$group_size\"" : "";
5030 print "<td class=\"sha1\"";
5031 print " title=\"". esc_html($author) . ", $date\"";
5032 print "$rowspan>";
5033 print $cgi->a({-href => href(action=>"commit",
5034 hash=>$full_rev,
5035 file_name=>$file_name)},
5036 esc_html($short_rev));
5037 if ($group_size >= 2) {
5038 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
5039 if (@author_initials) {
5040 print "<br />" .
5041 esc_html(join('', @author_initials));
5042 # or join('.', ...)
5045 print "</td>\n";
5046 print "<td class=\"extra_column\" $rowspan>". esc_html($author) . "</td>";
5047 print "<td class=\"extra_column\" $rowspan>". $date . "</td>";
5049 # 'previous' <sha1 of parent commit> <filename at commit>
5050 if (exists $meta->{'previous'} &&
5051 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
5052 $meta->{'parent'} = $1;
5053 $meta->{'file_parent'} = unquote($2);
5055 my $linenr_commit =
5056 exists($meta->{'parent'}) ?
5057 $meta->{'parent'} : $full_rev;
5058 my $linenr_filename =
5059 exists($meta->{'file_parent'}) ?
5060 $meta->{'file_parent'} : unquote($meta->{'filename'});
5061 my $blamed = href(action => 'blame',
5062 file_name => $linenr_filename,
5063 hash_base => $linenr_commit);
5064 print "<td class=\"linenr\">";
5065 print $cgi->a({ -href => "$blamed#l$orig_lineno",
5066 -class => "linenr" },
5067 esc_html($lineno));
5068 print "</td>";
5069 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
5070 print "</tr>\n";
5073 print "</table>\n";
5074 print "</div>";
5075 close $fd
5076 or print "Reading blob failed\n";
5078 if ($type eq 'incremental') {
5079 print "<script type=\"text/javascript\">\n";
5080 print "startBlame(\"" . href(action=>"blame_data", hash_base=>$hash_base, file_name=>$file_name) . "\", \"" .
5081 href(-partial_query=>1) . "\");\n";
5082 print "</script>\n";
5085 # page footer
5086 git_footer_html();
5089 sub git_blame_incremental {
5090 git_blame_common('incremental');
5093 sub git_blame {
5094 git_blame_common('oneshot');
5097 sub git_tags {
5098 my $head = git_get_head_hash($project);
5099 git_header_html();
5100 git_print_page_nav('','', $head,undef,$head);
5101 git_print_header_div('summary', $project);
5103 my @tagslist = git_get_tags_list();
5104 if (@tagslist) {
5105 git_tags_body(\@tagslist);
5107 git_footer_html();
5110 sub git_heads {
5111 my $head = git_get_head_hash($project);
5112 git_header_html();
5113 git_print_page_nav('','', $head,undef,$head);
5114 git_print_header_div('summary', $project);
5116 my @headslist = git_get_heads_list();
5117 if (@headslist) {
5118 git_heads_body(\@headslist, $head);
5120 git_footer_html();
5123 sub git_blob_plain {
5124 my $type = shift;
5125 my $expires;
5127 if (!defined $hash) {
5128 if (defined $file_name) {
5129 my $base = $hash_base || git_get_head_hash($project);
5130 $hash = git_get_hash_by_path($base, $file_name, "blob")
5131 or die_error(404, "Cannot find file");
5132 } else {
5133 die_error(400, "No file name defined");
5135 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5136 # blobs defined by non-textual hash id's can be cached
5137 $expires = "+1d";
5140 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5141 or die_error(500, "Open git-cat-file blob '$hash' failed");
5143 # content-type (can include charset)
5144 $type = blob_contenttype($fd, $file_name, $type);
5146 # "save as" filename, even when no $file_name is given
5147 my $save_as = "$hash";
5148 if (defined $file_name) {
5149 $save_as = $file_name;
5150 } elsif ($type =~ m/^text\//) {
5151 $save_as .= '.txt';
5154 # With XSS prevention on, blobs of all types except a few known safe
5155 # ones are served with "Content-Disposition: attachment" to make sure
5156 # they don't run in our security domain. For certain image types,
5157 # blob view writes an <img> tag referring to blob_plain view, and we
5158 # want to be sure not to break that by serving the image as an
5159 # attachment (though Firefox 3 doesn't seem to care).
5160 my $sandbox = $prevent_xss &&
5161 $type !~ m!^(?:text/plain|image/(?:gif|png|jpeg))$!;
5163 print $cgi->header(
5164 -type => $type,
5165 -expires => $expires,
5166 -content_disposition =>
5167 ($sandbox ? 'attachment' : 'inline')
5168 . '; filename="' . $save_as . '"');
5169 local $/ = undef;
5170 binmode STDOUT, ':raw';
5171 print <$fd>;
5172 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5173 close $fd;
5176 sub git_blob {
5177 my $expires;
5179 if (!defined $hash) {
5180 if (defined $file_name) {
5181 my $base = $hash_base || git_get_head_hash($project);
5182 $hash = git_get_hash_by_path($base, $file_name, "blob")
5183 or die_error(404, "Cannot find file");
5184 } else {
5185 die_error(400, "No file name defined");
5187 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5188 # blobs defined by non-textual hash id's can be cached
5189 $expires = "+1d";
5192 my $have_blame = gitweb_check_feature('blame');
5193 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
5194 or die_error(500, "Couldn't cat $file_name, $hash");
5195 my $mimetype = blob_mimetype($fd, $file_name);
5196 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
5197 close $fd;
5198 return git_blob_plain($mimetype);
5200 # we can have blame only for text/* mimetype
5201 $have_blame &&= ($mimetype =~ m!^text/!);
5203 git_header_html(undef, $expires);
5204 my $formats_nav = '';
5205 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5206 if (defined $file_name) {
5207 if ($have_blame) {
5208 $formats_nav .=
5209 $cgi->a({-href => href(action=>"blame", -replay=>1,
5210 -class => "blamelink")},
5211 "blame") .
5212 " | ";
5214 $formats_nav .=
5215 $cgi->a({-href => href(action=>"history", -replay=>1)},
5216 "history") .
5217 " | " .
5218 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5219 "raw") .
5220 " | " .
5221 $cgi->a({-href => href(action=>"blob",
5222 hash_base=>"HEAD", file_name=>$file_name)},
5223 "HEAD");
5224 } else {
5225 $formats_nav .=
5226 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
5227 "raw");
5229 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5230 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5231 } else {
5232 print "<div class=\"page_nav\">\n" .
5233 "<br/><br/></div>\n" .
5234 "<div class=\"title\">$hash</div>\n";
5236 git_print_page_path($file_name, "blob", $hash_base);
5237 print "<div class=\"page_body\">\n";
5238 if ($mimetype =~ m!^image/!) {
5239 print qq!<img type="$mimetype"!;
5240 if ($file_name) {
5241 print qq! alt="$file_name" title="$file_name"!;
5243 print qq! src="! .
5244 href(action=>"blob_plain", hash=>$hash,
5245 hash_base=>$hash_base, file_name=>$file_name) .
5246 qq!" />\n!;
5247 } else {
5248 my $nr;
5249 while (my $line = <$fd>) {
5250 chomp $line;
5251 $nr++;
5252 $line = untabify($line);
5253 printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
5254 $nr, $nr, $nr, esc_html($line, -nbsp=>1);
5257 close $fd
5258 or print "Reading blob failed.\n";
5259 print "</div>";
5260 git_footer_html();
5263 sub git_tree {
5264 if (!defined $hash_base) {
5265 $hash_base = "HEAD";
5267 if (!defined $hash) {
5268 if (defined $file_name) {
5269 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
5270 } else {
5271 $hash = $hash_base;
5274 die_error(404, "No such tree") unless defined($hash);
5276 my $show_sizes = gitweb_check_feature('show-sizes');
5277 my $have_blame = gitweb_check_feature('blame');
5279 my @entries = ();
5281 local $/ = "\0";
5282 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
5283 ($show_sizes ? '-l' : ()), @extra_options, $hash
5284 or die_error(500, "Open git-ls-tree failed");
5285 @entries = map { chomp; $_ } <$fd>;
5286 close $fd
5287 or die_error(404, "Reading tree failed");
5290 my $refs = git_get_references();
5291 my $ref = format_ref_marker($refs, $hash_base);
5292 git_header_html();
5293 my $basedir = '';
5294 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5295 my @views_nav = ();
5296 if (defined $file_name) {
5297 push @views_nav,
5298 $cgi->a({-href => href(action=>"history", -replay=>1)},
5299 "history"),
5300 $cgi->a({-href => href(action=>"tree",
5301 hash_base=>"HEAD", file_name=>$file_name)},
5302 "HEAD"),
5304 my $snapshot_links = format_snapshot_links($hash);
5305 if (defined $snapshot_links) {
5306 # FIXME: Should be available when we have no hash base as well.
5307 push @views_nav, $snapshot_links;
5309 git_print_page_nav('tree','', $hash_base, undef, undef,
5310 join(' | ', @views_nav));
5311 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
5312 } else {
5313 undef $hash_base;
5314 print "<div class=\"page_nav\">\n";
5315 print "<br/><br/></div>\n";
5316 print "<div class=\"title\">$hash</div>\n";
5318 if (defined $file_name) {
5319 $basedir = $file_name;
5320 if ($basedir ne '' && substr($basedir, -1) ne '/') {
5321 $basedir .= '/';
5323 git_print_page_path($file_name, 'tree', $hash_base);
5325 print "<div class=\"page_body\">\n";
5326 print "<table class=\"tree\">\n";
5327 my $alternate = 1;
5328 # '..' (top directory) link if possible
5329 if (defined $hash_base &&
5330 defined $file_name && $file_name =~ m![^/]+$!) {
5331 if ($alternate) {
5332 print "<tr class=\"dark\">\n";
5333 } else {
5334 print "<tr class=\"light\">\n";
5336 $alternate ^= 1;
5338 my $up = $file_name;
5339 $up =~ s!/?[^/]+$!!;
5340 undef $up unless $up;
5341 # based on git_print_tree_entry
5342 print '<td class="mode">' . mode_str('040000') . "</td>\n";
5343 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
5344 print '<td class="list">';
5345 print $cgi->a({-href => href(action=>"tree",
5346 hash_base=>$hash_base,
5347 file_name=>$up)},
5348 "..");
5349 print "</td>\n";
5350 print "<td class=\"link\"></td>\n";
5352 print "</tr>\n";
5354 foreach my $line (@entries) {
5355 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
5357 if ($alternate) {
5358 print "<tr class=\"dark\">\n";
5359 } else {
5360 print "<tr class=\"light\">\n";
5362 $alternate ^= 1;
5364 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
5366 print "</tr>\n";
5368 print "</table>\n" .
5369 "</div>";
5370 git_footer_html();
5373 sub git_snapshot {
5374 my $format = $input_params{'snapshot_format'};
5375 if (!@snapshot_fmts) {
5376 die_error(403, "Snapshots not allowed");
5378 # default to first supported snapshot format
5379 $format ||= $snapshot_fmts[0];
5380 if ($format !~ m/^[a-z0-9]+$/) {
5381 die_error(400, "Invalid snapshot format parameter");
5382 } elsif (!exists($known_snapshot_formats{$format})) {
5383 die_error(400, "Unknown snapshot format");
5384 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
5385 die_error(403, "Snapshot format not allowed");
5386 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
5387 die_error(403, "Unsupported snapshot format");
5390 if (!defined $hash) {
5391 $hash = git_get_head_hash($project);
5394 my $name = $project;
5395 $name =~ s,([^/])/*\.git$,$1,;
5396 $name = basename($name);
5397 my $filename = to_utf8($name);
5398 $name =~ s/\047/\047\\\047\047/g;
5399 my $cmd;
5400 $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
5401 $cmd = quote_command(
5402 git_cmd(), 'archive',
5403 "--format=$known_snapshot_formats{$format}{'format'}",
5404 "--prefix=$name/", $hash);
5405 if (exists $known_snapshot_formats{$format}{'compressor'}) {
5406 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
5409 print $cgi->header(
5410 -type => $known_snapshot_formats{$format}{'type'},
5411 -content_disposition => 'inline; filename="' . "$filename" . '"',
5412 -status => '200 OK');
5414 open my $fd, "-|", $cmd
5415 or die_error(500, "Execute git-archive failed");
5416 binmode STDOUT, ':raw';
5417 print <$fd>;
5418 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
5419 close $fd;
5422 sub git_log {
5423 my $head = git_get_head_hash($project);
5424 if (!defined $hash) {
5425 $hash = $head;
5427 if (!defined $page) {
5428 $page = 0;
5430 my $refs = git_get_references();
5432 my @commitlist = parse_commits($hash, 101, (100 * $page));
5434 my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#commitlist >= 100);
5436 my ($patch_max) = gitweb_get_feature('patches');
5437 if ($patch_max) {
5438 if ($patch_max < 0 || @commitlist <= $patch_max) {
5439 $paging_nav .= " &sdot; " .
5440 $cgi->a({-href => href(action=>"patches", -replay=>1)},
5441 "patches");
5445 git_header_html();
5446 git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
5448 if (!@commitlist) {
5449 my %co = parse_commit($hash);
5451 git_print_header_div('summary', $project);
5452 print "<div class=\"page_body\"> Last change $co{'age_string'}.<br/><br/></div>\n";
5454 my $to = ($#commitlist >= 99) ? (99) : ($#commitlist);
5455 for (my $i = 0; $i <= $to; $i++) {
5456 my %co = %{$commitlist[$i]};
5457 next if !%co;
5458 my $commit = $co{'id'};
5459 my $ref = format_ref_marker($refs, $commit);
5460 my %ad = parse_date($co{'author_epoch'});
5461 git_print_header_div('commit',
5462 "<span class=\"age\">$co{'age_string'}</span>" .
5463 esc_html($co{'title'}) . $ref,
5464 $commit);
5465 print "<div class=\"title_text\">\n" .
5466 "<div class=\"log_link\">\n" .
5467 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5468 " | " .
5469 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5470 " | " .
5471 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5472 "<br/>\n" .
5473 "</div>\n";
5474 git_print_authorship(\%co, -tag => 'span');
5475 print "<br/>\n</div>\n";
5477 print "<div class=\"log_body\">\n";
5478 git_print_log($co{'comment'}, -final_empty_line=> 1);
5479 print "</div>\n";
5481 if ($#commitlist >= 100) {
5482 print "<div class=\"page_nav\">\n";
5483 print $cgi->a({-href => href(-replay=>1, page=>$page+1),
5484 -accesskey => "n", -title => "Alt-n"}, "next");
5485 print "</div>\n";
5487 git_footer_html();
5490 sub git_commit {
5491 $hash ||= $hash_base || "HEAD";
5492 my %co = parse_commit($hash)
5493 or die_error(404, "Unknown commit object");
5495 my $parent = $co{'parent'};
5496 my $parents = $co{'parents'}; # listref
5498 # we need to prepare $formats_nav before any parameter munging
5499 my $formats_nav;
5500 if (!defined $parent) {
5501 # --root commitdiff
5502 $formats_nav .= '(initial)';
5503 } elsif (@$parents == 1) {
5504 # single parent commit
5505 $formats_nav .=
5506 '(parent: ' .
5507 $cgi->a({-href => href(action=>"commit",
5508 hash=>$parent)},
5509 esc_html(substr($parent, 0, 7))) .
5510 ')';
5511 } else {
5512 # merge commit
5513 $formats_nav .=
5514 '(merge: ' .
5515 join(' ', map {
5516 $cgi->a({-href => href(action=>"commit",
5517 hash=>$_)},
5518 esc_html(substr($_, 0, 7)));
5519 } @$parents ) .
5520 ')';
5522 if (gitweb_check_feature('patches') && @$parents <= 1) {
5523 $formats_nav .= " | " .
5524 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5525 "patch");
5528 if (!defined $parent) {
5529 $parent = "--root";
5531 my @difftree;
5532 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
5533 @diff_opts,
5534 (@$parents <= 1 ? $parent : '-c'),
5535 $hash, "--"
5536 or die_error(500, "Open git-diff-tree failed");
5537 @difftree = map { chomp; $_ } <$fd>;
5538 close $fd or die_error(404, "Reading git-diff-tree failed");
5540 # non-textual hash id's can be cached
5541 my $expires;
5542 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5543 $expires = "+1d";
5545 my $refs = git_get_references();
5546 my $ref = format_ref_marker($refs, $co{'id'});
5548 git_header_html(undef, $expires);
5549 git_print_page_nav('commit', '',
5550 $hash, $co{'tree'}, $hash,
5551 $formats_nav);
5553 if (defined $co{'parent'}) {
5554 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
5555 } else {
5556 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
5558 print "<div class=\"title_text\">\n" .
5559 "<table class=\"object_header\">\n";
5560 git_print_authorship_rows(\%co);
5561 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
5562 print "<tr>" .
5563 "<td>tree</td>" .
5564 "<td class=\"sha1\">" .
5565 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
5566 class => "list"}, $co{'tree'}) .
5567 "</td>" .
5568 "<td class=\"link\">" .
5569 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
5570 "tree");
5571 my $snapshot_links = format_snapshot_links($hash);
5572 if (defined $snapshot_links) {
5573 print " | " . $snapshot_links;
5575 print "</td>" .
5576 "</tr>\n";
5578 foreach my $par (@$parents) {
5579 print "<tr>" .
5580 "<td>parent</td>" .
5581 "<td class=\"sha1\">" .
5582 $cgi->a({-href => href(action=>"commit", hash=>$par),
5583 class => "list"}, $par) .
5584 "</td>" .
5585 "<td class=\"link\">" .
5586 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
5587 " | " .
5588 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
5589 "</td>" .
5590 "</tr>\n";
5592 print "</table>".
5593 "</div>\n";
5595 print "<div class=\"page_body\">\n";
5596 git_print_log($co{'comment'});
5597 print "</div>\n";
5599 git_difftree_body(\@difftree, $hash, @$parents);
5601 git_footer_html();
5604 sub git_object {
5605 # object is defined by:
5606 # - hash or hash_base alone
5607 # - hash_base and file_name
5608 my $type;
5610 # - hash or hash_base alone
5611 if ($hash || ($hash_base && !defined $file_name)) {
5612 my $object_id = $hash || $hash_base;
5614 open my $fd, "-|", quote_command(
5615 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
5616 or die_error(404, "Object does not exist");
5617 $type = <$fd>;
5618 chomp $type;
5619 close $fd
5620 or die_error(404, "Object does not exist");
5622 # - hash_base and file_name
5623 } elsif ($hash_base && defined $file_name) {
5624 $file_name =~ s,/+$,,;
5626 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
5627 or die_error(404, "Base object does not exist");
5629 # here errors should not hapen
5630 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
5631 or die_error(500, "Open git-ls-tree failed");
5632 my $line = <$fd>;
5633 close $fd;
5635 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
5636 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
5637 die_error(404, "File or directory for given base does not exist");
5639 $type = $2;
5640 $hash = $3;
5641 } else {
5642 die_error(400, "Not enough information to find object");
5645 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
5646 hash=>$hash, hash_base=>$hash_base,
5647 file_name=>$file_name),
5648 -status => '302 Found');
5651 sub git_blobdiff {
5652 my $format = shift || 'html';
5654 my $fd;
5655 my @difftree;
5656 my %diffinfo;
5657 my $expires;
5659 # preparing $fd and %diffinfo for git_patchset_body
5660 # new style URI
5661 if (defined $hash_base && defined $hash_parent_base) {
5662 if (defined $file_name) {
5663 # read raw output
5664 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5665 $hash_parent_base, $hash_base,
5666 "--", (defined $file_parent ? $file_parent : ()), $file_name
5667 or die_error(500, "Open git-diff-tree failed");
5668 @difftree = map { chomp; $_ } <$fd>;
5669 close $fd
5670 or die_error(404, "Reading git-diff-tree failed");
5671 @difftree
5672 or die_error(404, "Blob diff not found");
5674 } elsif (defined $hash &&
5675 $hash =~ /[0-9a-fA-F]{40}/) {
5676 # try to find filename from $hash
5678 # read filtered raw output
5679 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5680 $hash_parent_base, $hash_base, "--"
5681 or die_error(500, "Open git-diff-tree failed");
5682 @difftree =
5683 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
5684 # $hash == to_id
5685 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
5686 map { chomp; $_ } <$fd>;
5687 close $fd
5688 or die_error(404, "Reading git-diff-tree failed");
5689 @difftree
5690 or die_error(404, "Blob diff not found");
5692 } else {
5693 die_error(400, "Missing one of the blob diff parameters");
5696 if (@difftree > 1) {
5697 die_error(400, "Ambiguous blob diff specification");
5700 %diffinfo = parse_difftree_raw_line($difftree[0]);
5701 $file_parent ||= $diffinfo{'from_file'} || $file_name;
5702 $file_name ||= $diffinfo{'to_file'};
5704 $hash_parent ||= $diffinfo{'from_id'};
5705 $hash ||= $diffinfo{'to_id'};
5707 # non-textual hash id's can be cached
5708 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
5709 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
5710 $expires = '+1d';
5713 # open patch output
5714 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5715 '-p', ($format eq 'html' ? "--full-index" : ()),
5716 $hash_parent_base, $hash_base,
5717 "--", (defined $file_parent ? $file_parent : ()), $file_name
5718 or die_error(500, "Open git-diff-tree failed");
5721 # old/legacy style URI -- not generated anymore since 1.4.3.
5722 if (!%diffinfo) {
5723 die_error('404 Not Found', "Missing one of the blob diff parameters")
5726 # header
5727 if ($format eq 'html') {
5728 my $formats_nav =
5729 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
5730 "raw");
5731 git_header_html(undef, $expires);
5732 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
5733 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
5734 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
5735 } else {
5736 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
5737 print "<div class=\"title\">$hash vs $hash_parent</div>\n";
5739 if (defined $file_name) {
5740 git_print_page_path($file_name, "blob", $hash_base);
5741 } else {
5742 print "<div class=\"page_path\"></div>\n";
5745 } elsif ($format eq 'plain') {
5746 print $cgi->header(
5747 -type => 'text/plain',
5748 -charset => 'utf-8',
5749 -expires => $expires,
5750 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
5752 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5754 } else {
5755 die_error(400, "Unknown blobdiff format");
5758 # patch
5759 if ($format eq 'html') {
5760 print "<div class=\"page_body\">\n";
5762 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
5763 close $fd;
5765 print "</div>\n"; # class="page_body"
5766 git_footer_html();
5768 } else {
5769 while (my $line = <$fd>) {
5770 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
5771 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
5773 print $line;
5775 last if $line =~ m!^\+\+\+!;
5777 local $/ = undef;
5778 print <$fd>;
5779 close $fd;
5783 sub git_blobdiff_plain {
5784 git_blobdiff('plain');
5787 sub git_commitdiff {
5788 my %params = @_;
5789 my $format = $params{-format} || 'html';
5791 my ($patch_max) = gitweb_get_feature('patches');
5792 if ($format eq 'patch') {
5793 die_error(403, "Patch view not allowed") unless $patch_max;
5796 $hash ||= $hash_base || "HEAD";
5797 my %co = parse_commit($hash)
5798 or die_error(404, "Unknown commit object");
5800 # choose format for commitdiff for merge
5801 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
5802 $hash_parent = '--cc';
5804 # we need to prepare $formats_nav before almost any parameter munging
5805 my $formats_nav;
5806 if ($format eq 'html') {
5807 $formats_nav =
5808 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
5809 "raw");
5810 if ($patch_max && @{$co{'parents'}} <= 1) {
5811 $formats_nav .= " | " .
5812 $cgi->a({-href => href(action=>"patch", -replay=>1)},
5813 "patch");
5816 if (defined $hash_parent &&
5817 $hash_parent ne '-c' && $hash_parent ne '--cc') {
5818 # commitdiff with two commits given
5819 my $hash_parent_short = $hash_parent;
5820 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
5821 $hash_parent_short = substr($hash_parent, 0, 7);
5823 $formats_nav .=
5824 ' (from';
5825 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
5826 if ($co{'parents'}[$i] eq $hash_parent) {
5827 $formats_nav .= ' parent ' . ($i+1);
5828 last;
5831 $formats_nav .= ': ' .
5832 $cgi->a({-href => href(action=>"commitdiff",
5833 hash=>$hash_parent)},
5834 esc_html($hash_parent_short)) .
5835 ')';
5836 } elsif (!$co{'parent'}) {
5837 # --root commitdiff
5838 $formats_nav .= ' (initial)';
5839 } elsif (scalar @{$co{'parents'}} == 1) {
5840 # single parent commit
5841 $formats_nav .=
5842 ' (parent: ' .
5843 $cgi->a({-href => href(action=>"commitdiff",
5844 hash=>$co{'parent'})},
5845 esc_html(substr($co{'parent'}, 0, 7))) .
5846 ')';
5847 } else {
5848 # merge commit
5849 if ($hash_parent eq '--cc') {
5850 $formats_nav .= ' | ' .
5851 $cgi->a({-href => href(action=>"commitdiff",
5852 hash=>$hash, hash_parent=>'-c')},
5853 'combined');
5854 } else { # $hash_parent eq '-c'
5855 $formats_nav .= ' | ' .
5856 $cgi->a({-href => href(action=>"commitdiff",
5857 hash=>$hash, hash_parent=>'--cc')},
5858 'compact');
5860 $formats_nav .=
5861 ' (merge: ' .
5862 join(' ', map {
5863 $cgi->a({-href => href(action=>"commitdiff",
5864 hash=>$_)},
5865 esc_html(substr($_, 0, 7)));
5866 } @{$co{'parents'}} ) .
5867 ')';
5871 my $hash_parent_param = $hash_parent;
5872 if (!defined $hash_parent_param) {
5873 # --cc for multiple parents, --root for parentless
5874 $hash_parent_param =
5875 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
5878 # read commitdiff
5879 my $fd;
5880 my @difftree;
5881 if ($format eq 'html') {
5882 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5883 "--no-commit-id", "--patch-with-raw", "--full-index",
5884 $hash_parent_param, $hash, "--"
5885 or die_error(500, "Open git-diff-tree failed");
5887 while (my $line = <$fd>) {
5888 chomp $line;
5889 # empty line ends raw part of diff-tree output
5890 last unless $line;
5891 push @difftree, scalar parse_difftree_raw_line($line);
5894 } elsif ($format eq 'plain') {
5895 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
5896 '-p', $hash_parent_param, $hash, "--"
5897 or die_error(500, "Open git-diff-tree failed");
5898 } elsif ($format eq 'patch') {
5899 # For commit ranges, we limit the output to the number of
5900 # patches specified in the 'patches' feature.
5901 # For single commits, we limit the output to a single patch,
5902 # diverging from the git-format-patch default.
5903 my @commit_spec = ();
5904 if ($hash_parent) {
5905 if ($patch_max > 0) {
5906 push @commit_spec, "-$patch_max";
5908 push @commit_spec, '-n', "$hash_parent..$hash";
5909 } else {
5910 if ($params{-single}) {
5911 push @commit_spec, '-1';
5912 } else {
5913 if ($patch_max > 0) {
5914 push @commit_spec, "-$patch_max";
5916 push @commit_spec, "-n";
5918 push @commit_spec, '--root', $hash;
5920 open $fd, "-|", git_cmd(), "format-patch", '--encoding=utf8',
5921 '--stdout', @commit_spec
5922 or die_error(500, "Open git-format-patch failed");
5923 } else {
5924 die_error(400, "Unknown commitdiff format");
5927 # non-textual hash id's can be cached
5928 my $expires;
5929 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
5930 $expires = "+1d";
5933 # write commit message
5934 if ($format eq 'html') {
5935 my $refs = git_get_references();
5936 my $ref = format_ref_marker($refs, $co{'id'});
5938 git_header_html(undef, $expires);
5939 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
5940 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
5941 print "<div class=\"title_text\">\n" .
5942 "<table class=\"object_header\">\n";
5943 git_print_authorship_rows(\%co);
5944 print "</table>".
5945 "</div>\n";
5946 print "<div class=\"page_body\">\n";
5947 if (@{$co{'comment'}} > 1) {
5948 print "<div class=\"log\">\n";
5949 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
5950 print "</div>\n"; # class="log"
5953 } elsif ($format eq 'plain') {
5954 my $refs = git_get_references("tags");
5955 my $tagname = git_get_rev_name_tags($hash);
5956 my $filename = basename($project) . "-$hash.patch";
5958 print $cgi->header(
5959 -type => 'text/plain',
5960 -charset => 'utf-8',
5961 -expires => $expires,
5962 -content_disposition => 'inline; filename="' . "$filename" . '"');
5963 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
5964 print "From: " . to_utf8($co{'author'}) . "\n";
5965 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
5966 print "Subject: " . to_utf8($co{'title'}) . "\n";
5968 print "X-Git-Tag: $tagname\n" if $tagname;
5969 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
5971 foreach my $line (@{$co{'comment'}}) {
5972 print to_utf8($line) . "\n";
5974 print "---\n\n";
5975 } elsif ($format eq 'patch') {
5976 my $filename = basename($project) . "-$hash.patch";
5978 print $cgi->header(
5979 -type => 'text/plain',
5980 -charset => 'utf-8',
5981 -expires => $expires,
5982 -content_disposition => 'inline; filename="' . "$filename" . '"');
5985 # write patch
5986 if ($format eq 'html') {
5987 my $use_parents = !defined $hash_parent ||
5988 $hash_parent eq '-c' || $hash_parent eq '--cc';
5989 git_difftree_body(\@difftree, $hash,
5990 $use_parents ? @{$co{'parents'}} : $hash_parent);
5991 print "<br/>\n";
5993 git_patchset_body($fd, \@difftree, $hash,
5994 $use_parents ? @{$co{'parents'}} : $hash_parent);
5995 close $fd;
5996 print "</div>\n"; # class="page_body"
5997 git_footer_html();
5999 } elsif ($format eq 'plain') {
6000 local $/ = undef;
6001 print <$fd>;
6002 close $fd
6003 or print "Reading git-diff-tree failed\n";
6004 } elsif ($format eq 'patch') {
6005 local $/ = undef;
6006 print <$fd>;
6007 close $fd
6008 or print "Reading git-format-patch failed\n";
6012 sub git_commitdiff_plain {
6013 git_commitdiff(-format => 'plain');
6016 # format-patch-style patches
6017 sub git_patch {
6018 git_commitdiff(-format => 'patch', -single => 1);
6021 sub git_patches {
6022 git_commitdiff(-format => 'patch');
6025 sub git_history {
6026 if (!defined $hash_base) {
6027 $hash_base = git_get_head_hash($project);
6029 if (!defined $page) {
6030 $page = 0;
6032 my $ftype;
6033 my %co = parse_commit($hash_base)
6034 or die_error(404, "Unknown commit object");
6036 my $refs = git_get_references();
6037 my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
6039 my @commitlist = parse_commits($hash_base, 101, (100 * $page),
6040 $file_name, "--full-history")
6041 or die_error(404, "No such file or directory on given branch");
6043 if (!defined $hash && defined $file_name) {
6044 # some commits could have deleted file in question,
6045 # and not have it in tree, but one of them has to have it
6046 for (my $i = 0; $i <= @commitlist; $i++) {
6047 $hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
6048 last if defined $hash;
6051 if (defined $hash) {
6052 $ftype = git_get_type($hash);
6054 if (!defined $ftype) {
6055 die_error(500, "Unknown type of object");
6058 my $paging_nav = '';
6059 if ($page > 0) {
6060 $paging_nav .=
6061 $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
6062 file_name=>$file_name)},
6063 "first");
6064 $paging_nav .= " &sdot; " .
6065 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6066 -accesskey => "p", -title => "Alt-p"}, "prev");
6067 } else {
6068 $paging_nav .= "first";
6069 $paging_nav .= " &sdot; prev";
6071 my $next_link = '';
6072 if ($#commitlist >= 100) {
6073 $next_link =
6074 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6075 -accesskey => "n", -title => "Alt-n"}, "next");
6076 $paging_nav .= " &sdot; $next_link";
6077 } else {
6078 $paging_nav .= " &sdot; next";
6081 git_header_html();
6082 git_print_page_nav('history','', $hash_base,$co{'tree'},$hash_base, $paging_nav);
6083 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6084 git_print_page_path($file_name, $ftype, $hash_base);
6086 git_history_body(\@commitlist, 0, 99,
6087 $refs, $hash_base, $ftype, $next_link);
6089 git_footer_html();
6092 sub git_search {
6093 gitweb_check_feature('search') or die_error(403, "Search is disabled");
6094 if (!defined $searchtext) {
6095 die_error(400, "Text field is empty");
6097 if (!defined $hash) {
6098 $hash = git_get_head_hash($project);
6100 my %co = parse_commit($hash);
6101 if (!%co) {
6102 die_error(404, "Unknown commit object");
6104 if (!defined $page) {
6105 $page = 0;
6108 $searchtype ||= 'commit';
6109 if ($searchtype eq 'pickaxe') {
6110 # pickaxe may take all resources of your box and run for several minutes
6111 # with every query - so decide by yourself how public you make this feature
6112 gitweb_check_feature('pickaxe')
6113 or die_error(403, "Pickaxe is disabled");
6115 if ($searchtype eq 'grep') {
6116 gitweb_check_feature('grep')
6117 or die_error(403, "Grep is disabled");
6120 git_header_html();
6122 if ($searchtype eq 'commit' or $searchtype eq 'author' or $searchtype eq 'committer') {
6123 my $greptype;
6124 if ($searchtype eq 'commit') {
6125 $greptype = "--grep=";
6126 } elsif ($searchtype eq 'author') {
6127 $greptype = "--author=";
6128 } elsif ($searchtype eq 'committer') {
6129 $greptype = "--committer=";
6131 $greptype .= $searchtext;
6132 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6133 $greptype, '--regexp-ignore-case',
6134 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6136 my $paging_nav = '';
6137 if ($page > 0) {
6138 $paging_nav .=
6139 $cgi->a({-href => href(action=>"search", hash=>$hash,
6140 searchtext=>$searchtext,
6141 searchtype=>$searchtype)},
6142 "first");
6143 $paging_nav .= " &sdot; " .
6144 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6145 -accesskey => "p", -title => "Alt-p"}, "prev");
6146 } else {
6147 $paging_nav .= "first";
6148 $paging_nav .= " &sdot; prev";
6150 my $next_link = '';
6151 if ($#commitlist >= 100) {
6152 $next_link =
6153 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6154 -accesskey => "n", -title => "Alt-n"}, "next");
6155 $paging_nav .= " &sdot; $next_link";
6156 } else {
6157 $paging_nav .= " &sdot; next";
6160 if ($#commitlist >= 100) {
6163 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6164 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6165 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6168 if ($searchtype eq 'pickaxe') {
6169 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6170 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6172 print "<table class=\"pickaxe search\">\n";
6173 my $alternate = 1;
6174 local $/ = "\n";
6175 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
6176 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6177 ($search_use_regexp ? '--pickaxe-regex' : ());
6178 undef %co;
6179 my @files;
6180 while (my $line = <$fd>) {
6181 chomp $line;
6182 next unless $line;
6184 my %set = parse_difftree_raw_line($line);
6185 if (defined $set{'commit'}) {
6186 # finish previous commit
6187 if (%co) {
6188 print "</td>\n" .
6189 "<td class=\"link\">" .
6190 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6191 " | " .
6192 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6193 print "</td>\n" .
6194 "</tr>\n";
6197 if ($alternate) {
6198 print "<tr class=\"dark\">\n";
6199 } else {
6200 print "<tr class=\"light\">\n";
6202 $alternate ^= 1;
6203 %co = parse_commit($set{'commit'});
6204 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6205 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6206 "<td><i>$author</i></td>\n" .
6207 "<td>" .
6208 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6209 -class => "list subject"},
6210 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6211 } elsif (defined $set{'to_id'}) {
6212 next if ($set{'to_id'} =~ m/^0{40}$/);
6214 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6215 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6216 -class => "list"},
6217 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6218 "<br/>\n";
6221 close $fd;
6223 # finish last commit (warning: repetition!)
6224 if (%co) {
6225 print "</td>\n" .
6226 "<td class=\"link\">" .
6227 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6228 " | " .
6229 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6230 print "</td>\n" .
6231 "</tr>\n";
6234 print "</table>\n";
6237 if ($searchtype eq 'grep') {
6238 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6239 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6241 print "<table class=\"grep_search\">\n";
6242 my $alternate = 1;
6243 my $matches = 0;
6244 local $/ = "\n";
6245 open my $fd, "-|", git_cmd(), 'grep', '-n',
6246 $search_use_regexp ? ('-E', '-i') : '-F',
6247 $searchtext, $co{'tree'};
6248 my $lastfile = '';
6249 while (my $line = <$fd>) {
6250 chomp $line;
6251 my ($file, $lno, $ltext, $binary);
6252 last if ($matches++ > 1000);
6253 if ($line =~ /^Binary file (.+) matches$/) {
6254 $file = $1;
6255 $binary = 1;
6256 } else {
6257 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
6259 if ($file ne $lastfile) {
6260 $lastfile and print "</td></tr>\n";
6261 if ($alternate++) {
6262 print "<tr class=\"dark\">\n";
6263 } else {
6264 print "<tr class=\"light\">\n";
6266 print "<td class=\"list\">".
6267 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6268 file_name=>"$file"),
6269 -class => "list"}, esc_path($file));
6270 print "</td><td>\n";
6271 $lastfile = $file;
6273 if ($binary) {
6274 print "<div class=\"binary\">Binary file</div>\n";
6275 } else {
6276 $ltext = untabify($ltext);
6277 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6278 $ltext = esc_html($1, -nbsp=>1);
6279 $ltext .= '<span class="match">';
6280 $ltext .= esc_html($2, -nbsp=>1);
6281 $ltext .= '</span>';
6282 $ltext .= esc_html($3, -nbsp=>1);
6283 } else {
6284 $ltext = esc_html($ltext, -nbsp=>1);
6286 print "<div class=\"pre\">" .
6287 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
6288 file_name=>"$file").'#l'.$lno,
6289 -class => "linenr"}, sprintf('%4i', $lno))
6290 . ' ' . $ltext . "</div>\n";
6293 if ($lastfile) {
6294 print "</td></tr>\n";
6295 if ($matches > 1000) {
6296 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6298 } else {
6299 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6301 close $fd;
6303 print "</table>\n";
6305 git_footer_html();
6308 sub git_search_help {
6309 git_header_html();
6310 git_print_page_nav('','', $hash,$hash,$hash);
6311 print <<EOT;
6312 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
6313 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
6314 the pattern entered is recognized as the POSIX extended
6315 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
6316 insensitive).</p>
6317 <dl>
6318 <dt><b>commit</b></dt>
6319 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
6321 my $have_grep = gitweb_check_feature('grep');
6322 if ($have_grep) {
6323 print <<EOT;
6324 <dt><b>grep</b></dt>
6325 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
6326 a different one) are searched for the given pattern. On large trees, this search can take
6327 a while and put some strain on the server, so please use it with some consideration. Note that
6328 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
6329 case-sensitive.</dd>
6332 print <<EOT;
6333 <dt><b>author</b></dt>
6334 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
6335 <dt><b>committer</b></dt>
6336 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
6338 my $have_pickaxe = gitweb_check_feature('pickaxe');
6339 if ($have_pickaxe) {
6340 print <<EOT;
6341 <dt><b>pickaxe</b></dt>
6342 <dd>All commits that caused the string to appear or disappear from any file (changes that
6343 added, removed or "modified" the string) will be listed. This search can take a while and
6344 takes a lot of strain on the server, so please use it wisely. Note that since you may be
6345 interested even in changes just changing the case as well, this search is case sensitive.</dd>
6348 print "</dl>\n";
6349 git_footer_html();
6352 sub git_shortlog {
6353 my $head = git_get_head_hash($project);
6354 if (!defined $hash) {
6355 $hash = $head;
6357 if (!defined $page) {
6358 $page = 0;
6360 my $refs = git_get_references();
6362 my $commit_hash = $hash;
6363 if (defined $hash_parent) {
6364 $commit_hash = "$hash_parent..$hash";
6366 my @commitlist = parse_commits($commit_hash, 101, (100 * $page));
6368 my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#commitlist >= 100);
6369 my $next_link = '';
6370 if ($#commitlist >= 100) {
6371 $next_link =
6372 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6373 -accesskey => "n", -title => "Alt-n"}, "next");
6375 my $patch_max = gitweb_check_feature('patches');
6376 if ($patch_max) {
6377 if ($patch_max < 0 || @commitlist <= $patch_max) {
6378 $paging_nav .= " &sdot; " .
6379 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6380 "patches");
6384 git_header_html();
6385 git_print_page_nav('shortlog','', $hash,$hash,$hash, $paging_nav);
6386 git_print_header_div('summary', $project);
6388 git_shortlog_body(\@commitlist, 0, 99, $refs, $next_link);
6390 git_footer_html();
6393 ## ......................................................................
6394 ## feeds (RSS, Atom; OPML)
6396 sub git_feed {
6397 my $format = shift || 'atom';
6398 my $have_blame = gitweb_check_feature('blame');
6400 # Atom: http://www.atomenabled.org/developers/syndication/
6401 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
6402 if ($format ne 'rss' && $format ne 'atom') {
6403 die_error(400, "Unknown web feed format");
6406 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
6407 my $head = $hash || 'HEAD';
6408 my @commitlist = parse_commits($head, 150, 0, $file_name);
6410 my %latest_commit;
6411 my %latest_date;
6412 my $content_type = "application/$format+xml";
6413 if (defined $cgi->http('HTTP_ACCEPT') &&
6414 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
6415 # browser (feed reader) prefers text/xml
6416 $content_type = 'text/xml';
6418 if (defined($commitlist[0])) {
6419 %latest_commit = %{$commitlist[0]};
6420 my $latest_epoch = $latest_commit{'committer_epoch'};
6421 %latest_date = parse_date($latest_epoch);
6422 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
6423 if (defined $if_modified) {
6424 my $since;
6425 if (eval { require HTTP::Date; 1; }) {
6426 $since = HTTP::Date::str2time($if_modified);
6427 } elsif (eval { require Time::ParseDate; 1; }) {
6428 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
6430 if (defined $since && $latest_epoch <= $since) {
6431 print $cgi->header(
6432 -type => $content_type,
6433 -charset => 'utf-8',
6434 -last_modified => $latest_date{'rfc2822'},
6435 -status => '304 Not Modified');
6436 return;
6439 print $cgi->header(
6440 -type => $content_type,
6441 -charset => 'utf-8',
6442 -last_modified => $latest_date{'rfc2822'});
6443 } else {
6444 print $cgi->header(
6445 -type => $content_type,
6446 -charset => 'utf-8');
6449 # Optimization: skip generating the body if client asks only
6450 # for Last-Modified date.
6451 return if ($cgi->request_method() eq 'HEAD');
6453 # header variables
6454 my $title = "$site_name - $project/$action";
6455 my $feed_type = 'log';
6456 if (defined $hash) {
6457 $title .= " - '$hash'";
6458 $feed_type = 'branch log';
6459 if (defined $file_name) {
6460 $title .= " :: $file_name";
6461 $feed_type = 'history';
6463 } elsif (defined $file_name) {
6464 $title .= " - $file_name";
6465 $feed_type = 'history';
6467 $title .= " $feed_type";
6468 my $descr = git_get_project_description($project);
6469 if (defined $descr) {
6470 $descr = esc_html($descr);
6471 } else {
6472 $descr = "$project " .
6473 ($format eq 'rss' ? 'RSS' : 'Atom') .
6474 " feed";
6476 my $owner = git_get_project_owner($project);
6477 $owner = esc_html($owner);
6479 #header
6480 my $alt_url;
6481 if (defined $file_name) {
6482 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
6483 } elsif (defined $hash) {
6484 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
6485 } else {
6486 $alt_url = href(-full=>1, action=>"summary");
6488 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
6489 if ($format eq 'rss') {
6490 print <<XML;
6491 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
6492 <channel>
6494 print "<title>$title</title>\n" .
6495 "<link>$alt_url</link>\n" .
6496 "<description>$descr</description>\n" .
6497 "<language>en</language>\n" .
6498 # project owner is responsible for 'editorial' content
6499 "<managingEditor>$owner</managingEditor>\n";
6500 if (defined $logo || defined $favicon) {
6501 # prefer the logo to the favicon, since RSS
6502 # doesn't allow both
6503 my $img = esc_url($logo || $favicon);
6504 print "<image>\n" .
6505 "<url>$img</url>\n" .
6506 "<title>$title</title>\n" .
6507 "<link>$alt_url</link>\n" .
6508 "</image>\n";
6510 if (%latest_date) {
6511 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
6512 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
6514 print "<generator>gitweb v.$version/$git_version</generator>\n";
6515 } elsif ($format eq 'atom') {
6516 print <<XML;
6517 <feed xmlns="http://www.w3.org/2005/Atom">
6519 print "<title>$title</title>\n" .
6520 "<subtitle>$descr</subtitle>\n" .
6521 '<link rel="alternate" type="text/html" href="' .
6522 $alt_url . '" />' . "\n" .
6523 '<link rel="self" type="' . $content_type . '" href="' .
6524 $cgi->self_url() . '" />' . "\n" .
6525 "<id>" . href(-full=>1) . "</id>\n" .
6526 # use project owner for feed author
6527 "<author><name>$owner</name></author>\n";
6528 if (defined $favicon) {
6529 print "<icon>" . esc_url($favicon) . "</icon>\n";
6531 if (defined $logo_url) {
6532 # not twice as wide as tall: 72 x 27 pixels
6533 print "<logo>" . esc_url($logo) . "</logo>\n";
6535 if (! %latest_date) {
6536 # dummy date to keep the feed valid until commits trickle in:
6537 print "<updated>1970-01-01T00:00:00Z</updated>\n";
6538 } else {
6539 print "<updated>$latest_date{'iso-8601'}</updated>\n";
6541 print "<generator version='$version/$git_version'>gitweb</generator>\n";
6544 # contents
6545 for (my $i = 0; $i <= $#commitlist; $i++) {
6546 my %co = %{$commitlist[$i]};
6547 my $commit = $co{'id'};
6548 # we read 150, we always show 30 and the ones more recent than 48 hours
6549 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
6550 last;
6552 my %cd = parse_date($co{'author_epoch'});
6554 # get list of changed files
6555 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6556 $co{'parent'} || "--root",
6557 $co{'id'}, "--", (defined $file_name ? $file_name : ())
6558 or next;
6559 my @difftree = map { chomp; $_ } <$fd>;
6560 close $fd
6561 or next;
6563 # print element (entry, item)
6564 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
6565 if ($format eq 'rss') {
6566 print "<item>\n" .
6567 "<title>" . esc_html($co{'title'}) . "</title>\n" .
6568 "<author>" . esc_html($co{'author'}) . "</author>\n" .
6569 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
6570 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
6571 "<link>$co_url</link>\n" .
6572 "<description>" . esc_html($co{'title'}) . "</description>\n" .
6573 "<content:encoded>" .
6574 "<![CDATA[\n";
6575 } elsif ($format eq 'atom') {
6576 print "<entry>\n" .
6577 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
6578 "<updated>$cd{'iso-8601'}</updated>\n" .
6579 "<author>\n" .
6580 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
6581 if ($co{'author_email'}) {
6582 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
6584 print "</author>\n" .
6585 # use committer for contributor
6586 "<contributor>\n" .
6587 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
6588 if ($co{'committer_email'}) {
6589 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
6591 print "</contributor>\n" .
6592 "<published>$cd{'iso-8601'}</published>\n" .
6593 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
6594 "<id>$co_url</id>\n" .
6595 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
6596 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
6598 my $comment = $co{'comment'};
6599 print "<pre>\n";
6600 foreach my $line (@$comment) {
6601 $line = esc_html($line);
6602 print "$line\n";
6604 print "</pre><ul>\n";
6605 foreach my $difftree_line (@difftree) {
6606 my %difftree = parse_difftree_raw_line($difftree_line);
6607 next if !$difftree{'from_id'};
6609 my $file = $difftree{'file'} || $difftree{'to_file'};
6611 print "<li>" .
6612 "[" .
6613 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
6614 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
6615 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
6616 file_name=>$file, file_parent=>$difftree{'from_file'}),
6617 -title => "diff"}, 'D');
6618 if ($have_blame) {
6619 print $cgi->a({-href => href(-full=>1, action=>"blame",
6620 file_name=>$file, hash_base=>$commit), -class => "blamelink",
6621 -title => "blame"}, 'B');
6623 # if this is not a feed of a file history
6624 if (!defined $file_name || $file_name ne $file) {
6625 print $cgi->a({-href => href(-full=>1, action=>"history",
6626 file_name=>$file, hash=>$commit),
6627 -title => "history"}, 'H');
6629 $file = esc_path($file);
6630 print "] ".
6631 "$file</li>\n";
6633 if ($format eq 'rss') {
6634 print "</ul>]]>\n" .
6635 "</content:encoded>\n" .
6636 "</item>\n";
6637 } elsif ($format eq 'atom') {
6638 print "</ul>\n</div>\n" .
6639 "</content>\n" .
6640 "</entry>\n";
6644 # end of feed
6645 if ($format eq 'rss') {
6646 print "</channel>\n</rss>\n";
6647 } elsif ($format eq 'atom') {
6648 print "</feed>\n";
6652 sub git_rss {
6653 git_feed('rss');
6656 sub git_atom {
6657 git_feed('atom');
6660 sub git_opml {
6661 my @list = git_get_projects_list();
6663 print $cgi->header(
6664 -type => 'text/xml',
6665 -charset => 'utf-8',
6666 -content_disposition => 'inline; filename="opml.xml"');
6668 print <<XML;
6669 <?xml version="1.0" encoding="utf-8"?>
6670 <opml version="1.0">
6671 <head>
6672 <title>$site_name OPML Export</title>
6673 </head>
6674 <body>
6675 <outline text="git RSS feeds">
6678 foreach my $pr (@list) {
6679 my %proj = %$pr;
6680 my $head = git_get_head_hash($proj{'path'});
6681 if (!defined $head) {
6682 next;
6684 $git_dir = "$projectroot/$proj{'path'}";
6685 my %co = parse_commit($head);
6686 if (!%co) {
6687 next;
6690 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
6691 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
6692 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
6693 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
6695 print <<XML;
6696 </outline>
6697 </body>
6698 </opml>