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
13 use CGI qw(:standard :escapeHTML -nosticky);
14 use CGI::Util qw(unescape);
15 use CGI::Carp qw(fatalsToBrowser set_message);
19 use File::Basename qw(basename);
20 use Time::HiRes qw(gettimeofday tv_interval);
21 binmode STDOUT, ':utf8';
23 our $t0 = [ gettimeofday() ];
24 our $number_of_git_cmds = 0;
27 CGI->compile() if $ENV{'MOD_PERL'};
30 our $version = "++GIT_VERSION++";
32 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
36 our $my_url = $cgi->url();
37 our $my_uri = $cgi->url(-absolute => 1);
39 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
40 # needed and used only for URLs with nonempty PATH_INFO
41 our $base_url = $my_url;
43 # When the script is used as DirectoryIndex, the URL does not contain the name
44 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
45 # have to do it ourselves. We make $path_info global because it's also used
48 # Another issue with the script being the DirectoryIndex is that the resulting
49 # $my_url data is not the full script URL: this is good, because we want
50 # generated links to keep implying the script name if it wasn't explicitly
51 # indicated in the URL we're handling, but it means that $my_url cannot be used
53 # Therefore, if we needed to strip PATH_INFO, then we know that we have
54 # to build the base URL ourselves:
55 our $path_info = $ENV{"PATH_INFO"};
57 if ($my_url =~ s,\Q$path_info\E$,, &&
58 $my_uri =~ s,\Q$path_info\E$,, &&
59 defined $ENV{'SCRIPT_NAME'}) {
60 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
64 # target of the home link on top of all pages
65 our $home_link = $my_uri || "/";
68 # core git executable to use
69 # this can just be "git" if your webserver has a sensible PATH
70 our $GIT = "++GIT_BINDIR++/git";
72 # absolute fs-path which will be prepended to the project path
73 #our $projectroot = "/pub/scm";
74 our $projectroot = "++GITWEB_PROJECTROOT++";
76 # fs traversing limit for getting project list
77 # the number is relative to the projectroot
78 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
80 # string of the home link on top of all pages
81 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
83 # name of your site or organization to appear in page titles
84 # replace this with something more descriptive for clearer bookmarks
85 our $site_name = "++GITWEB_SITENAME++"
86 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
88 # filename of html text to include at top of each page
89 our $site_header = "++GITWEB_SITE_HEADER++";
90 # html text to include at home page
91 our $home_text = "++GITWEB_HOMETEXT++";
92 # filename of html text to include at bottom of each page
93 our $site_footer = "++GITWEB_SITE_FOOTER++";
96 our @stylesheets = ("++GITWEB_CSS++");
97 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
98 our $stylesheet = undef;
99 # URI of GIT logo (72x27 size)
100 our $logo = "++GITWEB_LOGO++";
101 # URI of GIT favicon, assumed to be image/png type
102 our $favicon = "++GITWEB_FAVICON++";
103 # URI of gitweb.js (JavaScript code for gitweb)
104 our $javascript = "++GITWEB_JS++";
106 # URI and label (title) of GIT logo link
107 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
108 #our $logo_label = "git documentation";
109 our $logo_url = "http://git-scm.com/";
110 our $logo_label = "git homepage";
112 # source of projects list
113 our $projects_list = "++GITWEB_LIST++";
115 # the width (in characters) of the projects list "Description" column
116 our $projects_list_description_width = 25;
118 # group projects by category on the projects list
119 # (enabled if this variable evaluates to true)
120 our $projects_list_group_categories = 0;
122 # default category if none specified
123 # (leave the empty string for no category)
124 our $project_list_default_category = "";
126 # default order of projects list
127 # valid values are none, project, descr, owner, and age
128 our $default_projects_order = "project";
130 # show repository only if this file exists
131 # (only effective if this variable evaluates to true)
132 our $export_ok = "++GITWEB_EXPORT_OK++";
134 # show repository only if this subroutine returns true
135 # when given the path to the project, for example:
136 # sub { return -e "$_[0]/git-daemon-export-ok"; }
137 our $export_auth_hook = undef;
139 # only allow viewing of repositories also shown on the overview page
140 our $strict_export = "++GITWEB_STRICT_EXPORT++";
142 # list of git base URLs used for URL to where fetch project from,
143 # i.e. full URL is "$git_base_url/$project"
144 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
146 # default blob_plain mimetype and default charset for text/plain blob
147 our $default_blob_plain_mimetype = 'text/plain';
148 our $default_text_plain_charset = undef;
150 # file to use for guessing MIME types before trying /etc/mime.types
151 # (relative to the current git repository)
152 our $mimetypes_file = undef;
154 # assume this charset if line contains non-UTF-8 characters;
155 # it should be valid encoding (see Encoding::Supported(3pm) for list),
156 # for which encoding all byte sequences are valid, for example
157 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
158 # could be even 'utf-8' for the old behavior)
159 our $fallback_encoding = 'latin1';
161 # rename detection options for git-diff and git-diff-tree
162 # - default is '-M', with the cost proportional to
163 # (number of removed files) * (number of new files).
164 # - more costly is '-C' (which implies '-M'), with the cost proportional to
165 # (number of changed files + number of removed files) * (number of new files)
166 # - even more costly is '-C', '--find-copies-harder' with cost
167 # (number of files in the original tree) * (number of new files)
168 # - one might want to include '-B' option, e.g. '-B', '-M'
169 our @diff_opts = ('-M'); # taken from git_commit
171 # Disables features that would allow repository owners to inject script into
173 our $prevent_xss = 0;
175 # Path to the highlight executable to use (must be the one from
176 # http://www.andre-simon.de due to assumptions about parameters and output).
177 # Useful if highlight is not installed on your webserver's PATH.
178 # [Default: highlight]
179 our $highlight_bin = "++HIGHLIGHT_BIN++";
181 # information about snapshot formats that gitweb is capable of serving
182 our %known_snapshot_formats = (
184 # 'display' => display name,
185 # 'type' => mime type,
186 # 'suffix' => filename suffix,
187 # 'format' => --format for git-archive,
188 # 'compressor' => [compressor command and arguments]
189 # (array reference, optional)
190 # 'disabled' => boolean (optional)}
193 'display' => 'tar.gz',
194 'type' => 'application/x-gzip',
195 'suffix' => '.tar.gz',
197 'compressor' => ['gzip', '-n']},
200 'display' => 'tar.bz2',
201 'type' => 'application/x-bzip2',
202 'suffix' => '.tar.bz2',
204 'compressor' => ['bzip2']},
207 'display' => 'tar.xz',
208 'type' => 'application/x-xz',
209 'suffix' => '.tar.xz',
211 'compressor' => ['xz'],
216 'type' => 'application/x-zip',
221 # Aliases so we understand old gitweb.snapshot values in repository
223 our %known_snapshot_format_aliases = (
228 # backward compatibility: legacy gitweb config support
229 'x-gzip' => undef, 'gz' => undef,
230 'x-bzip2' => undef, 'bz2' => undef,
231 'x-zip' => undef, '' => undef,
234 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
235 # are changed, it may be appropriate to change these values too via
242 # Used to set the maximum load that we will still respond to gitweb queries.
243 # If server load exceed this value then return "503 server busy" error.
244 # If gitweb cannot determined server load, it is taken to be 0.
245 # Leave it undefined (or set to 'undef') to turn off load checking.
248 # configuration for 'highlight' (http://www.andre-simon.de/)
250 our %highlight_basename = (
253 'SConstruct' => 'py', # SCons equivalent of Makefile
254 'Makefile' => 'make',
257 our %highlight_ext = (
258 # main extensions, defining name of syntax;
259 # see files in /usr/share/highlight/langDefs/ directory
261 qw(py c cpp rb java css php sh pl js tex bib xml awk bat ini spec tcl sql make),
262 # alternate extensions, see /etc/highlight/filetypes.conf
264 map { $_ => 'sh' } qw(bash zsh ksh),
265 map { $_ => 'cpp' } qw(cxx c++ cc),
266 map { $_ => 'php' } qw(php3 php4 php5 phps),
267 map { $_ => 'pl' } qw(perl pm), # perhaps also 'cgi'
268 map { $_ => 'make'} qw(mak mk),
269 map { $_ => 'xml' } qw(xhtml html htm),
272 # You define site-wide feature defaults here; override them with
273 # $GITWEB_CONFIG as necessary.
276 # 'sub' => feature-sub (subroutine),
277 # 'override' => allow-override (boolean),
278 # 'default' => [ default options...] (array reference)}
280 # if feature is overridable (it means that allow-override has true value),
281 # then feature-sub will be called with default options as parameters;
282 # return value of feature-sub indicates if to enable specified feature
284 # if there is no 'sub' key (no feature-sub), then feature cannot be
287 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
288 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
291 # Enable the 'blame' blob view, showing the last commit that modified
292 # each line in the file. This can be very CPU-intensive.
294 # To enable system wide have in $GITWEB_CONFIG
295 # $feature{'blame'}{'default'} = [1];
296 # To have project specific config enable override in $GITWEB_CONFIG
297 # $feature{'blame'}{'override'} = 1;
298 # and in project config gitweb.blame = 0|1;
300 'sub' => sub { feature_bool('blame', @_) },
304 # Enable the 'snapshot' link, providing a compressed archive of any
305 # tree. This can potentially generate high traffic if you have large
308 # Value is a list of formats defined in %known_snapshot_formats that
310 # To disable system wide have in $GITWEB_CONFIG
311 # $feature{'snapshot'}{'default'} = [];
312 # To have project specific config enable override in $GITWEB_CONFIG
313 # $feature{'snapshot'}{'override'} = 1;
314 # and in project config, a comma-separated list of formats or "none"
315 # to disable. Example: gitweb.snapshot = tbz2,zip;
317 'sub' => \&feature_snapshot,
319 'default' => ['tgz']},
321 # Enable text search, which will list the commits which match author,
322 # committer or commit text to a given string. Enabled by default.
323 # Project specific override is not supported.
325 # Note that this controls all search features, which means that if
326 # it is disabled, then 'grep' and 'pickaxe' search would also be
332 # Enable grep search, which will list the files in currently selected
333 # tree containing the given string. Enabled by default. This can be
334 # potentially CPU-intensive, of course.
335 # Note that you need to have 'search' feature enabled too.
337 # To enable system wide have in $GITWEB_CONFIG
338 # $feature{'grep'}{'default'} = [1];
339 # To have project specific config enable override in $GITWEB_CONFIG
340 # $feature{'grep'}{'override'} = 1;
341 # and in project config gitweb.grep = 0|1;
343 'sub' => sub { feature_bool('grep', @_) },
347 # Enable the pickaxe search, which will list the commits that modified
348 # a given string in a file. This can be practical and quite faster
349 # alternative to 'blame', but still potentially CPU-intensive.
350 # Note that you need to have 'search' feature enabled too.
352 # To enable system wide have in $GITWEB_CONFIG
353 # $feature{'pickaxe'}{'default'} = [1];
354 # To have project specific config enable override in $GITWEB_CONFIG
355 # $feature{'pickaxe'}{'override'} = 1;
356 # and in project config gitweb.pickaxe = 0|1;
358 'sub' => sub { feature_bool('pickaxe', @_) },
362 # Enable showing size of blobs in a 'tree' view, in a separate
363 # column, similar to what 'ls -l' does. This cost a bit of IO.
365 # To disable system wide have in $GITWEB_CONFIG
366 # $feature{'show-sizes'}{'default'} = [0];
367 # To have project specific config enable override in $GITWEB_CONFIG
368 # $feature{'show-sizes'}{'override'} = 1;
369 # and in project config gitweb.showsizes = 0|1;
371 'sub' => sub { feature_bool('showsizes', @_) },
375 # Make gitweb use an alternative format of the URLs which can be
376 # more readable and natural-looking: project name is embedded
377 # directly in the path and the query string contains other
378 # auxiliary information. All gitweb installations recognize
379 # URL in either format; this configures in which formats gitweb
382 # To enable system wide have in $GITWEB_CONFIG
383 # $feature{'pathinfo'}{'default'} = [1];
384 # Project specific override is not supported.
386 # Note that you will need to change the default location of CSS,
387 # favicon, logo and possibly other files to an absolute URL. Also,
388 # if gitweb.cgi serves as your indexfile, you will need to force
389 # $my_uri to contain the script name in your $GITWEB_CONFIG.
394 # Make gitweb consider projects in project root subdirectories
395 # to be forks of existing projects. Given project $projname.git,
396 # projects matching $projname/*.git will not be shown in the main
397 # projects list, instead a '+' mark will be added to $projname
398 # there and a 'forks' view will be enabled for the project, listing
399 # all the forks. If project list is taken from a file, forks have
400 # to be listed after the main project.
402 # To enable system wide have in $GITWEB_CONFIG
403 # $feature{'forks'}{'default'} = [1];
404 # Project specific override is not supported.
409 # Insert custom links to the action bar of all project pages.
410 # This enables you mainly to link to third-party scripts integrating
411 # into gitweb; e.g. git-browser for graphical history representation
412 # or custom web-based repository administration interface.
414 # The 'default' value consists of a list of triplets in the form
415 # (label, link, position) where position is the label after which
416 # to insert the link and link is a format string where %n expands
417 # to the project name, %f to the project path within the filesystem,
418 # %h to the current hash (h gitweb parameter) and %b to the current
419 # hash base (hb gitweb parameter); %% expands to %.
421 # To enable system wide have in $GITWEB_CONFIG e.g.
422 # $feature{'actions'}{'default'} = [('graphiclog',
423 # '/git-browser/by-commit.html?r=%n', 'summary')];
424 # Project specific override is not supported.
429 # Allow gitweb scan project content tags of project repository,
430 # and display the popular Web 2.0-ish "tag cloud" near the projects
431 # list. Note that this is something COMPLETELY different from the
434 # gitweb by itself can show existing tags, but it does not handle
435 # tagging itself; you need to do it externally, outside gitweb.
436 # The format is described in git_get_project_ctags() subroutine.
437 # You may want to install the HTML::TagCloud Perl module to get
438 # a pretty tag cloud instead of just a list of tags.
440 # To enable system wide have in $GITWEB_CONFIG
441 # $feature{'ctags'}{'default'} = [1];
442 # Project specific override is not supported.
444 # In the future whether ctags editing is enabled might depend
445 # on the value, but using 1 should always mean no editing of ctags.
450 # The maximum number of patches in a patchset generated in patch
451 # view. Set this to 0 or undef to disable patch view, or to a
452 # negative number to remove any limit.
454 # To disable system wide have in $GITWEB_CONFIG
455 # $feature{'patches'}{'default'} = [0];
456 # To have project specific config enable override in $GITWEB_CONFIG
457 # $feature{'patches'}{'override'} = 1;
458 # and in project config gitweb.patches = 0|n;
459 # where n is the maximum number of patches allowed in a patchset.
461 'sub' => \&feature_patches,
465 # Avatar support. When this feature is enabled, views such as
466 # shortlog or commit will display an avatar associated with
467 # the email of the committer(s) and/or author(s).
469 # Currently available providers are gravatar and picon.
470 # If an unknown provider is specified, the feature is disabled.
472 # Gravatar depends on Digest::MD5.
473 # Picon currently relies on the indiana.edu database.
475 # To enable system wide have in $GITWEB_CONFIG
476 # $feature{'avatar'}{'default'} = ['<provider>'];
477 # where <provider> is either gravatar or picon.
478 # To have project specific config enable override in $GITWEB_CONFIG
479 # $feature{'avatar'}{'override'} = 1;
480 # and in project config gitweb.avatar = <provider>;
482 'sub' => \&feature_avatar,
486 # Enable displaying how much time and how many git commands
487 # it took to generate and display page. Disabled by default.
488 # Project specific override is not supported.
493 # Enable turning some links into links to actions which require
494 # JavaScript to run (like 'blame_incremental'). Not enabled by
495 # default. Project specific override is currently not supported.
496 'javascript-actions' => {
500 # Enable and configure ability to change common timezone for dates
501 # in gitweb output via JavaScript. Enabled by default.
502 # Project specific override is not supported.
503 'javascript-timezone' => {
506 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
507 # or undef to turn off this feature
508 'gitweb_tz', # name of cookie where to store selected timezone
509 'datetime', # CSS class used to mark up dates for manipulation
512 # Syntax highlighting support. This is based on Daniel Svensson's
513 # and Sham Chukoury's work in gitweb-xmms2.git.
514 # It requires the 'highlight' program present in $PATH,
515 # and therefore is disabled by default.
517 # To enable system wide have in $GITWEB_CONFIG
518 # $feature{'highlight'}{'default'} = [1];
521 'sub' => sub { feature_bool('highlight', @_) },
525 # Enable displaying of remote heads in the heads list
527 # To enable system wide have in $GITWEB_CONFIG
528 # $feature{'remote_heads'}{'default'} = [1];
529 # To have project specific config enable override in $GITWEB_CONFIG
530 # $feature{'remote_heads'}{'override'} = 1;
531 # and in project config gitweb.remote_heads = 0|1;
533 'sub' => sub { feature_bool('remote_heads', @_) },
538 sub gitweb_get_feature {
540 return unless exists $feature{$name};
541 my ($sub, $override, @defaults) = (
542 $feature{$name}{'sub'},
543 $feature{$name}{'override'},
544 @{$feature{$name}{'default'}});
545 # project specific override is possible only if we have project
546 our $git_dir; # global variable, declared later
547 if (!$override || !defined $git_dir) {
551 warn "feature $name is not overridable";
554 return $sub->(@defaults);
557 # A wrapper to check if a given feature is enabled.
558 # With this, you can say
560 # my $bool_feat = gitweb_check_feature('bool_feat');
561 # gitweb_check_feature('bool_feat') or somecode;
565 # my ($bool_feat) = gitweb_get_feature('bool_feat');
566 # (gitweb_get_feature('bool_feat'))[0] or somecode;
568 sub gitweb_check_feature {
569 return (gitweb_get_feature(@_))[0];
575 my ($val) = git_get_project_config($key, '--bool');
579 } elsif ($val eq 'true') {
581 } elsif ($val eq 'false') {
586 sub feature_snapshot {
589 my ($val) = git_get_project_config('snapshot');
592 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
598 sub feature_patches {
599 my @val = (git_get_project_config('patches', '--int'));
609 my @val = (git_get_project_config('avatar'));
611 return @val ? @val : @_;
614 # checking HEAD file with -e is fragile if the repository was
615 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
617 sub check_head_link {
619 my $headfile = "$dir/HEAD";
620 return ((-e $headfile) ||
621 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
624 sub check_export_ok {
626 return (check_head_link($dir) &&
627 (!$export_ok || -e "$dir/$export_ok") &&
628 (!$export_auth_hook || $export_auth_hook->($dir)));
631 # process alternate names for backward compatibility
632 # filter out unsupported (unknown) snapshot formats
633 sub filter_snapshot_fmts {
637 exists $known_snapshot_format_aliases{$_} ?
638 $known_snapshot_format_aliases{$_} : $_} @fmts;
640 exists $known_snapshot_formats{$_} &&
641 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
644 # If it is set to code reference, it is code that it is to be run once per
645 # request, allowing updating configurations that change with each request,
646 # while running other code in config file only once.
648 # Otherwise, if it is false then gitweb would process config file only once;
649 # if it is true then gitweb config would be run for each request.
650 our $per_request_config = 1;
652 # read and parse gitweb config file given by its parameter.
653 # returns true on success, false on recoverable error, allowing
654 # to chain this subroutine, using first file that exists.
655 # dies on errors during parsing config file, as it is unrecoverable.
656 sub read_config_file {
657 my $filename = shift;
658 return unless defined $filename;
659 # die if there are errors parsing config file
668 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM);
669 sub evaluate_gitweb_config {
670 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
671 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
673 # use first config file that exists
674 read_config_file($GITWEB_CONFIG) or
675 read_config_file($GITWEB_CONFIG_SYSTEM);
678 # Get loadavg of system, to compare against $maxload.
679 # Currently it requires '/proc/loadavg' present to get loadavg;
680 # if it is not present it returns 0, which means no load checking.
682 if( -e '/proc/loadavg' ){
683 open my $fd, '<', '/proc/loadavg'
685 my @load = split(/\s+/, scalar <$fd>);
688 # The first three columns measure CPU and IO utilization of the last one,
689 # five, and 10 minute periods. The fourth column shows the number of
690 # currently running processes and the total number of processes in the m/n
691 # format. The last column displays the last process ID used.
692 return $load[0] || 0;
694 # additional checks for load average should go here for things that don't export
700 # version of the core git binary
702 sub evaluate_git_version {
703 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
704 $number_of_git_cmds++;
708 if (defined $maxload && get_loadavg() > $maxload) {
709 die_error(503, "The load average on the server is too high");
713 # ======================================================================
714 # input validation and dispatch
716 # input parameters can be collected from a variety of sources (presently, CGI
717 # and PATH_INFO), so we define an %input_params hash that collects them all
718 # together during validation: this allows subsequent uses (e.g. href()) to be
719 # agnostic of the parameter origin
721 our %input_params = ();
723 # input parameters are stored with the long parameter name as key. This will
724 # also be used in the href subroutine to convert parameters to their CGI
725 # equivalent, and since the href() usage is the most frequent one, we store
726 # the name -> CGI key mapping here, instead of the reverse.
728 # XXX: Warning: If you touch this, check the search form for updating,
731 our @cgi_param_mapping = (
739 hash_parent_base => "hpb",
744 snapshot_format => "sf",
745 extra_options => "opt",
746 search_use_regexp => "sr",
748 # this must be last entry (for manipulation from JavaScript)
751 our %cgi_param_mapping = @cgi_param_mapping;
753 # we will also need to know the possible actions, for validation
755 "blame" => \&git_blame,
756 "blame_incremental" => \&git_blame_incremental,
757 "blame_data" => \&git_blame_data,
758 "blobdiff" => \&git_blobdiff,
759 "blobdiff_plain" => \&git_blobdiff_plain,
760 "blob" => \&git_blob,
761 "blob_plain" => \&git_blob_plain,
762 "commitdiff" => \&git_commitdiff,
763 "commitdiff_plain" => \&git_commitdiff_plain,
764 "commit" => \&git_commit,
765 "forks" => \&git_forks,
766 "heads" => \&git_heads,
767 "history" => \&git_history,
769 "patch" => \&git_patch,
770 "patches" => \&git_patches,
771 "remotes" => \&git_remotes,
773 "atom" => \&git_atom,
774 "search" => \&git_search,
775 "search_help" => \&git_search_help,
776 "shortlog" => \&git_shortlog,
777 "summary" => \&git_summary,
779 "tags" => \&git_tags,
780 "tree" => \&git_tree,
781 "snapshot" => \&git_snapshot,
782 "object" => \&git_object,
783 # those below don't need $project
784 "opml" => \&git_opml,
785 "project_list" => \&git_project_list,
786 "project_index" => \&git_project_index,
789 # finally, we have the hash of allowed extra_options for the commands that
791 our %allowed_options = (
792 "--no-merges" => [ qw(rss atom log shortlog history) ],
795 # fill %input_params with the CGI parameters. All values except for 'opt'
796 # should be single values, but opt can be an array. We should probably
797 # build an array of parameters that can be multi-valued, but since for the time
798 # being it's only this one, we just single it out
799 sub evaluate_query_params {
802 while (my ($name, $symbol) = each %cgi_param_mapping) {
803 if ($symbol eq 'opt') {
804 $input_params{$name} = [ $cgi->param($symbol) ];
806 $input_params{$name} = $cgi->param($symbol);
811 # now read PATH_INFO and update the parameter list for missing parameters
812 sub evaluate_path_info {
813 return if defined $input_params{'project'};
814 return if !$path_info;
815 $path_info =~ s,^/+,,;
816 return if !$path_info;
818 # find which part of PATH_INFO is project
819 my $project = $path_info;
821 while ($project && !check_head_link("$projectroot/$project")) {
822 $project =~ s,/*[^/]*$,,;
824 return unless $project;
825 $input_params{'project'} = $project;
827 # do not change any parameters if an action is given using the query string
828 return if $input_params{'action'};
829 $path_info =~ s,^\Q$project\E/*,,;
831 # next, check if we have an action
832 my $action = $path_info;
834 if (exists $actions{$action}) {
835 $path_info =~ s,^$action/*,,;
836 $input_params{'action'} = $action;
839 # list of actions that want hash_base instead of hash, but can have no
840 # pathname (f) parameter
846 # we want to catch, among others
847 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
848 my ($parentrefname, $parentpathname, $refname, $pathname) =
849 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
851 # first, analyze the 'current' part
852 if (defined $pathname) {
853 # we got "branch:filename" or "branch:dir/"
854 # we could use git_get_type(branch:pathname), but:
855 # - it needs $git_dir
856 # - it does a git() call
857 # - the convention of terminating directories with a slash
858 # makes it superfluous
859 # - embedding the action in the PATH_INFO would make it even
861 $pathname =~ s,^/+,,;
862 if (!$pathname || substr($pathname, -1) eq "/") {
863 $input_params{'action'} ||= "tree";
866 # the default action depends on whether we had parent info
868 if ($parentrefname) {
869 $input_params{'action'} ||= "blobdiff_plain";
871 $input_params{'action'} ||= "blob_plain";
874 $input_params{'hash_base'} ||= $refname;
875 $input_params{'file_name'} ||= $pathname;
876 } elsif (defined $refname) {
877 # we got "branch". In this case we have to choose if we have to
878 # set hash or hash_base.
880 # Most of the actions without a pathname only want hash to be
881 # set, except for the ones specified in @wants_base that want
882 # hash_base instead. It should also be noted that hand-crafted
883 # links having 'history' as an action and no pathname or hash
884 # set will fail, but that happens regardless of PATH_INFO.
885 if (defined $parentrefname) {
886 # if there is parent let the default be 'shortlog' action
887 # (for http://git.example.com/repo.git/A..B links); if there
888 # is no parent, dispatch will detect type of object and set
889 # action appropriately if required (if action is not set)
890 $input_params{'action'} ||= "shortlog";
892 if ($input_params{'action'} &&
893 grep { $_ eq $input_params{'action'} } @wants_base) {
894 $input_params{'hash_base'} ||= $refname;
896 $input_params{'hash'} ||= $refname;
900 # next, handle the 'parent' part, if present
901 if (defined $parentrefname) {
902 # a missing pathspec defaults to the 'current' filename, allowing e.g.
903 # someproject/blobdiff/oldrev..newrev:/filename
904 if ($parentpathname) {
905 $parentpathname =~ s,^/+,,;
906 $parentpathname =~ s,/$,,;
907 $input_params{'file_parent'} ||= $parentpathname;
909 $input_params{'file_parent'} ||= $input_params{'file_name'};
911 # we assume that hash_parent_base is wanted if a path was specified,
912 # or if the action wants hash_base instead of hash
913 if (defined $input_params{'file_parent'} ||
914 grep { $_ eq $input_params{'action'} } @wants_base) {
915 $input_params{'hash_parent_base'} ||= $parentrefname;
917 $input_params{'hash_parent'} ||= $parentrefname;
921 # for the snapshot action, we allow URLs in the form
922 # $project/snapshot/$hash.ext
923 # where .ext determines the snapshot and gets removed from the
924 # passed $refname to provide the $hash.
926 # To be able to tell that $refname includes the format extension, we
927 # require the following two conditions to be satisfied:
928 # - the hash input parameter MUST have been set from the $refname part
929 # of the URL (i.e. they must be equal)
930 # - the snapshot format MUST NOT have been defined already (e.g. from
932 # It's also useless to try any matching unless $refname has a dot,
933 # so we check for that too
934 if (defined $input_params{'action'} &&
935 $input_params{'action'} eq 'snapshot' &&
936 defined $refname && index($refname, '.') != -1 &&
937 $refname eq $input_params{'hash'} &&
938 !defined $input_params{'snapshot_format'}) {
939 # We loop over the known snapshot formats, checking for
940 # extensions. Allowed extensions are both the defined suffix
941 # (which includes the initial dot already) and the snapshot
942 # format key itself, with a prepended dot
943 while (my ($fmt, $opt) = each %known_snapshot_formats) {
945 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
949 # a valid suffix was found, so set the snapshot format
950 # and reset the hash parameter
951 $input_params{'snapshot_format'} = $fmt;
952 $input_params{'hash'} = $hash;
953 # we also set the format suffix to the one requested
954 # in the URL: this way a request for e.g. .tgz returns
955 # a .tgz instead of a .tar.gz
956 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
962 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
963 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
964 $searchtext, $search_regexp);
965 sub evaluate_and_validate_params {
966 our $action = $input_params{'action'};
967 if (defined $action) {
968 if (!validate_action($action)) {
969 die_error(400, "Invalid action parameter");
973 # parameters which are pathnames
974 our $project = $input_params{'project'};
975 if (defined $project) {
976 if (!validate_project($project)) {
978 die_error(404, "No such project");
982 our $file_name = $input_params{'file_name'};
983 if (defined $file_name) {
984 if (!validate_pathname($file_name)) {
985 die_error(400, "Invalid file parameter");
989 our $file_parent = $input_params{'file_parent'};
990 if (defined $file_parent) {
991 if (!validate_pathname($file_parent)) {
992 die_error(400, "Invalid file parent parameter");
996 # parameters which are refnames
997 our $hash = $input_params{'hash'};
999 if (!validate_refname($hash)) {
1000 die_error(400, "Invalid hash parameter");
1004 our $hash_parent = $input_params{'hash_parent'};
1005 if (defined $hash_parent) {
1006 if (!validate_refname($hash_parent)) {
1007 die_error(400, "Invalid hash parent parameter");
1011 our $hash_base = $input_params{'hash_base'};
1012 if (defined $hash_base) {
1013 if (!validate_refname($hash_base)) {
1014 die_error(400, "Invalid hash base parameter");
1018 our @extra_options = @{$input_params{'extra_options'}};
1019 # @extra_options is always defined, since it can only be (currently) set from
1020 # CGI, and $cgi->param() returns the empty array in array context if the param
1022 foreach my $opt (@extra_options) {
1023 if (not exists $allowed_options{$opt}) {
1024 die_error(400, "Invalid option parameter");
1026 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1027 die_error(400, "Invalid option parameter for this action");
1031 our $hash_parent_base = $input_params{'hash_parent_base'};
1032 if (defined $hash_parent_base) {
1033 if (!validate_refname($hash_parent_base)) {
1034 die_error(400, "Invalid hash parent base parameter");
1039 our $page = $input_params{'page'};
1040 if (defined $page) {
1041 if ($page =~ m/[^0-9]/) {
1042 die_error(400, "Invalid page parameter");
1046 our $searchtype = $input_params{'searchtype'};
1047 if (defined $searchtype) {
1048 if ($searchtype =~ m/[^a-z]/) {
1049 die_error(400, "Invalid searchtype parameter");
1053 our $search_use_regexp = $input_params{'search_use_regexp'};
1055 our $searchtext = $input_params{'searchtext'};
1057 if (defined $searchtext) {
1058 if (length($searchtext) < 2) {
1059 die_error(403, "At least two characters are required for search parameter");
1061 $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
1065 # path to the current git repository
1067 sub evaluate_git_dir {
1068 our $git_dir = "$projectroot/$project" if $project;
1071 our (@snapshot_fmts, $git_avatar);
1072 sub configure_gitweb_features {
1073 # list of supported snapshot formats
1074 our @snapshot_fmts = gitweb_get_feature('snapshot');
1075 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1077 # check that the avatar feature is set to a known provider name,
1078 # and for each provider check if the dependencies are satisfied.
1079 # if the provider name is invalid or the dependencies are not met,
1080 # reset $git_avatar to the empty string.
1081 our ($git_avatar) = gitweb_get_feature('avatar');
1082 if ($git_avatar eq 'gravatar') {
1083 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1084 } elsif ($git_avatar eq 'picon') {
1091 # custom error handler: 'die <message>' is Internal Server Error
1092 sub handle_errors_html {
1093 my $msg = shift; # it is already HTML escaped
1095 # to avoid infinite loop where error occurs in die_error,
1096 # change handler to default handler, disabling handle_errors_html
1097 set_message("Error occured when inside die_error:\n$msg");
1099 # you cannot jump out of die_error when called as error handler;
1100 # the subroutine set via CGI::Carp::set_message is called _after_
1101 # HTTP headers are already written, so it cannot write them itself
1102 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1104 set_message(\&handle_errors_html);
1108 if (!defined $action) {
1109 if (defined $hash) {
1110 $action = git_get_type($hash);
1111 } elsif (defined $hash_base && defined $file_name) {
1112 $action = git_get_type("$hash_base:$file_name");
1113 } elsif (defined $project) {
1114 $action = 'summary';
1116 $action = 'project_list';
1119 if (!defined($actions{$action})) {
1120 die_error(400, "Unknown action");
1122 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1124 die_error(400, "Project needed");
1126 $actions{$action}->();
1130 our $t0 = [ gettimeofday() ]
1132 our $number_of_git_cmds = 0;
1135 our $first_request = 1;
1140 if ($first_request) {
1141 evaluate_gitweb_config();
1142 evaluate_git_version();
1144 if ($per_request_config) {
1145 if (ref($per_request_config) eq 'CODE') {
1146 $per_request_config->();
1147 } elsif (!$first_request) {
1148 evaluate_gitweb_config();
1153 # $projectroot and $projects_list might be set in gitweb config file
1154 $projects_list ||= $projectroot;
1156 evaluate_query_params();
1157 evaluate_path_info();
1158 evaluate_and_validate_params();
1161 configure_gitweb_features();
1166 our $is_last_request = sub { 1 };
1167 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1170 sub configure_as_fcgi {
1172 our $CGI = 'CGI::Fast';
1174 my $request_number = 0;
1175 # let each child service 100 requests
1176 our $is_last_request = sub { ++$request_number > 100 };
1179 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1181 if $script_name =~ /\.fcgi$/;
1183 return unless (@ARGV);
1185 require Getopt::Long;
1186 Getopt::Long::GetOptions(
1187 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1188 'nproc|n=i' => sub {
1189 my ($arg, $val) = @_;
1190 return unless eval { require FCGI::ProcManager; 1; };
1191 my $proc_manager = FCGI::ProcManager->new({
1192 n_processes => $val,
1194 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1195 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1196 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1205 $pre_listen_hook->()
1206 if $pre_listen_hook;
1209 while ($cgi = $CGI->new()) {
1210 $pre_dispatch_hook->()
1211 if $pre_dispatch_hook;
1215 $post_dispatch_hook->()
1216 if $post_dispatch_hook;
1219 last REQUEST if ($is_last_request->());
1228 if (defined caller) {
1229 # wrapped in a subroutine processing requests,
1230 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1233 # pure CGI script, serving single request
1237 ## ======================================================================
1240 # possible values of extra options
1241 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1242 # -replay => 1 - start from a current view (replay with modifications)
1243 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1244 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1247 # default is to use -absolute url() i.e. $my_uri
1248 my $href = $params{-full} ? $my_url : $my_uri;
1250 # implicit -replay, must be first of implicit params
1251 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1253 $params{'project'} = $project unless exists $params{'project'};
1255 if ($params{-replay}) {
1256 while (my ($name, $symbol) = each %cgi_param_mapping) {
1257 if (!exists $params{$name}) {
1258 $params{$name} = $input_params{$name};
1263 my $use_pathinfo = gitweb_check_feature('pathinfo');
1264 if (defined $params{'project'} &&
1265 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1266 # try to put as many parameters as possible in PATH_INFO:
1269 # - hash_parent or hash_parent_base:/file_parent
1270 # - hash or hash_base:/filename
1271 # - the snapshot_format as an appropriate suffix
1273 # When the script is the root DirectoryIndex for the domain,
1274 # $href here would be something like http://gitweb.example.com/
1275 # Thus, we strip any trailing / from $href, to spare us double
1276 # slashes in the final URL
1279 # Then add the project name, if present
1280 $href .= "/".esc_path_info($params{'project'});
1281 delete $params{'project'};
1283 # since we destructively absorb parameters, we keep this
1284 # boolean that remembers if we're handling a snapshot
1285 my $is_snapshot = $params{'action'} eq 'snapshot';
1287 # Summary just uses the project path URL, any other action is
1289 if (defined $params{'action'}) {
1290 $href .= "/".esc_path_info($params{'action'})
1291 unless $params{'action'} eq 'summary';
1292 delete $params{'action'};
1295 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1296 # stripping nonexistent or useless pieces
1297 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1298 || $params{'hash_parent'} || $params{'hash'});
1299 if (defined $params{'hash_base'}) {
1300 if (defined $params{'hash_parent_base'}) {
1301 $href .= esc_path_info($params{'hash_parent_base'});
1302 # skip the file_parent if it's the same as the file_name
1303 if (defined $params{'file_parent'}) {
1304 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1305 delete $params{'file_parent'};
1306 } elsif ($params{'file_parent'} !~ /\.\./) {
1307 $href .= ":/".esc_path_info($params{'file_parent'});
1308 delete $params{'file_parent'};
1312 delete $params{'hash_parent'};
1313 delete $params{'hash_parent_base'};
1314 } elsif (defined $params{'hash_parent'}) {
1315 $href .= esc_path_info($params{'hash_parent'}). "..";
1316 delete $params{'hash_parent'};
1319 $href .= esc_path_info($params{'hash_base'});
1320 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1321 $href .= ":/".esc_path_info($params{'file_name'});
1322 delete $params{'file_name'};
1324 delete $params{'hash'};
1325 delete $params{'hash_base'};
1326 } elsif (defined $params{'hash'}) {
1327 $href .= esc_path_info($params{'hash'});
1328 delete $params{'hash'};
1331 # If the action was a snapshot, we can absorb the
1332 # snapshot_format parameter too
1334 my $fmt = $params{'snapshot_format'};
1335 # snapshot_format should always be defined when href()
1336 # is called, but just in case some code forgets, we
1337 # fall back to the default
1338 $fmt ||= $snapshot_fmts[0];
1339 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1340 delete $params{'snapshot_format'};
1344 # now encode the parameters explicitly
1346 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1347 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1348 if (defined $params{$name}) {
1349 if (ref($params{$name}) eq "ARRAY") {
1350 foreach my $par (@{$params{$name}}) {
1351 push @result, $symbol . "=" . esc_param($par);
1354 push @result, $symbol . "=" . esc_param($params{$name});
1358 $href .= "?" . join(';', @result) if scalar @result;
1360 # final transformation: trailing spaces must be escaped (URI-encoded)
1361 $href =~ s/(\s+)$/CGI::escape($1)/e;
1363 if ($params{-anchor}) {
1364 $href .= "#".esc_param($params{-anchor});
1371 ## ======================================================================
1372 ## validation, quoting/unquoting and escaping
1374 sub validate_action {
1375 my $input = shift || return undef;
1376 return undef unless exists $actions{$input};
1380 sub validate_project {
1381 my $input = shift || return undef;
1382 if (!validate_pathname($input) ||
1383 !(-d "$projectroot/$input") ||
1384 !check_export_ok("$projectroot/$input") ||
1385 ($strict_export && !project_in_list($input))) {
1392 sub validate_pathname {
1393 my $input = shift || return undef;
1395 # no '.' or '..' as elements of path, i.e. no '.' nor '..'
1396 # at the beginning, at the end, and between slashes.
1397 # also this catches doubled slashes
1398 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1401 # no null characters
1402 if ($input =~ m!\0!) {
1408 sub validate_refname {
1409 my $input = shift || return undef;
1411 # textual hashes are O.K.
1412 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1415 # it must be correct pathname
1416 $input = validate_pathname($input)
1418 # restrictions on ref name according to git-check-ref-format
1419 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1425 # decode sequences of octets in utf8 into Perl's internal form,
1426 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1427 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1430 return undef unless defined $str;
1431 if (utf8::valid($str)) {
1435 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1439 # quote unsafe chars, but keep the slash, even when it's not
1440 # correct, but quoted slashes look too horrible in bookmarks
1443 return undef unless defined $str;
1444 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1449 # the quoting rules for path_info fragment are slightly different
1452 return undef unless defined $str;
1454 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1455 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1460 # quote unsafe chars in whole URL, so some characters cannot be quoted
1463 return undef unless defined $str;
1464 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1469 # quote unsafe characters in HTML attributes
1472 # for XHTML conformance escaping '"' to '"' is not enough
1473 return esc_html(@_);
1476 # replace invalid utf8 character with SUBSTITUTION sequence
1481 return undef unless defined $str;
1483 $str = to_utf8($str);
1484 $str = $cgi->escapeHTML($str);
1485 if ($opts{'-nbsp'}) {
1486 $str =~ s/ / /g;
1488 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1492 # quote control characters and escape filename to HTML
1497 return undef unless defined $str;
1499 $str = to_utf8($str);
1500 $str = $cgi->escapeHTML($str);
1501 if ($opts{'-nbsp'}) {
1502 $str =~ s/ / /g;
1504 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1508 # Make control characters "printable", using character escape codes (CEC)
1512 my %es = ( # character escape codes, aka escape sequences
1513 "\t" => '\t', # tab (HT)
1514 "\n" => '\n', # line feed (LF)
1515 "\r" => '\r', # carrige return (CR)
1516 "\f" => '\f', # form feed (FF)
1517 "\b" => '\b', # backspace (BS)
1518 "\a" => '\a', # alarm (bell) (BEL)
1519 "\e" => '\e', # escape (ESC)
1520 "\013" => '\v', # vertical tab (VT)
1521 "\000" => '\0', # nul character (NUL)
1523 my $chr = ( (exists $es{$cntrl})
1525 : sprintf('\%2x', ord($cntrl)) );
1526 if ($opts{-nohtml}) {
1529 return "<span class=\"cntrl\">$chr</span>";
1533 # Alternatively use unicode control pictures codepoints,
1534 # Unicode "printable representation" (PR)
1539 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1540 if ($opts{-nohtml}) {
1543 return "<span class=\"cntrl\">$chr</span>";
1547 # git may return quoted and escaped filenames
1553 my %es = ( # character escape codes, aka escape sequences
1554 't' => "\t", # tab (HT, TAB)
1555 'n' => "\n", # newline (NL)
1556 'r' => "\r", # return (CR)
1557 'f' => "\f", # form feed (FF)
1558 'b' => "\b", # backspace (BS)
1559 'a' => "\a", # alarm (bell) (BEL)
1560 'e' => "\e", # escape (ESC)
1561 'v' => "\013", # vertical tab (VT)
1564 if ($seq =~ m/^[0-7]{1,3}$/) {
1565 # octal char sequence
1566 return chr(oct($seq));
1567 } elsif (exists $es{$seq}) {
1568 # C escape sequence, aka character escape code
1571 # quoted ordinary character
1575 if ($str =~ m/^"(.*)"$/) {
1578 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1583 # escape tabs (convert tabs to spaces)
1587 while ((my $pos = index($line, "\t")) != -1) {
1588 if (my $count = (8 - ($pos % 8))) {
1589 my $spaces = ' ' x $count;
1590 $line =~ s/\t/$spaces/;
1597 sub project_in_list {
1598 my $project = shift;
1599 my @list = git_get_projects_list();
1600 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1603 ## ----------------------------------------------------------------------
1604 ## HTML aware string manipulation
1606 # Try to chop given string on a word boundary between position
1607 # $len and $len+$add_len. If there is no word boundary there,
1608 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1609 # (marking chopped part) would be longer than given string.
1613 my $add_len = shift || 10;
1614 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1616 # Make sure perl knows it is utf8 encoded so we don't
1617 # cut in the middle of a utf8 multibyte char.
1618 $str = to_utf8($str);
1620 # allow only $len chars, but don't cut a word if it would fit in $add_len
1621 # if it doesn't fit, cut it if it's still longer than the dots we would add
1622 # remove chopped character entities entirely
1624 # when chopping in the middle, distribute $len into left and right part
1625 # return early if chopping wouldn't make string shorter
1626 if ($where eq 'center') {
1627 return $str if ($len + 5 >= length($str)); # filler is length 5
1630 return $str if ($len + 4 >= length($str)); # filler is length 4
1633 # regexps: ending and beginning with word part up to $add_len
1634 my $endre = qr/.{$len}\w{0,$add_len}/;
1635 my $begre = qr/\w{0,$add_len}.{$len}/;
1637 if ($where eq 'left') {
1638 $str =~ m/^(.*?)($begre)$/;
1639 my ($lead, $body) = ($1, $2);
1640 if (length($lead) > 4) {
1643 return "$lead$body";
1645 } elsif ($where eq 'center') {
1646 $str =~ m/^($endre)(.*)$/;
1647 my ($left, $str) = ($1, $2);
1648 $str =~ m/^(.*?)($begre)$/;
1649 my ($mid, $right) = ($1, $2);
1650 if (length($mid) > 5) {
1653 return "$left$mid$right";
1656 $str =~ m/^($endre)(.*)$/;
1659 if (length($tail) > 4) {
1662 return "$body$tail";
1666 # takes the same arguments as chop_str, but also wraps a <span> around the
1667 # result with a title attribute if it does get chopped. Additionally, the
1668 # string is HTML-escaped.
1669 sub chop_and_escape_str {
1672 my $chopped = chop_str(@_);
1673 if ($chopped eq $str) {
1674 return esc_html($chopped);
1676 $str =~ s/[[:cntrl:]]/?/g;
1677 return $cgi->span({-title=>$str}, esc_html($chopped));
1681 ## ----------------------------------------------------------------------
1682 ## functions returning short strings
1684 # CSS class for given age value (in seconds)
1688 if (!defined $age) {
1690 } elsif ($age < 60*60*2) {
1692 } elsif ($age < 60*60*24*2) {
1699 # convert age in seconds to "nn units ago" string
1704 if ($age > 60*60*24*365*2) {
1705 $age_str = (int $age/60/60/24/365);
1706 $age_str .= " years ago";
1707 } elsif ($age > 60*60*24*(365/12)*2) {
1708 $age_str = int $age/60/60/24/(365/12);
1709 $age_str .= " months ago";
1710 } elsif ($age > 60*60*24*7*2) {
1711 $age_str = int $age/60/60/24/7;
1712 $age_str .= " weeks ago";
1713 } elsif ($age > 60*60*24*2) {
1714 $age_str = int $age/60/60/24;
1715 $age_str .= " days ago";
1716 } elsif ($age > 60*60*2) {
1717 $age_str = int $age/60/60;
1718 $age_str .= " hours ago";
1719 } elsif ($age > 60*2) {
1720 $age_str = int $age/60;
1721 $age_str .= " min ago";
1722 } elsif ($age > 2) {
1723 $age_str = int $age;
1724 $age_str .= " sec ago";
1726 $age_str .= " right now";
1732 S_IFINVALID => 0030000,
1733 S_IFGITLINK => 0160000,
1736 # submodule/subproject, a commit object reference
1740 return (($mode & S_IFMT) == S_IFGITLINK)
1743 # convert file mode in octal to symbolic file mode string
1745 my $mode = oct shift;
1747 if (S_ISGITLINK($mode)) {
1748 return 'm---------';
1749 } elsif (S_ISDIR($mode & S_IFMT)) {
1750 return 'drwxr-xr-x';
1751 } elsif (S_ISLNK($mode)) {
1752 return 'lrwxrwxrwx';
1753 } elsif (S_ISREG($mode)) {
1754 # git cares only about the executable bit
1755 if ($mode & S_IXUSR) {
1756 return '-rwxr-xr-x';
1758 return '-rw-r--r--';
1761 return '----------';
1765 # convert file mode in octal to file type string
1769 if ($mode !~ m/^[0-7]+$/) {
1775 if (S_ISGITLINK($mode)) {
1777 } elsif (S_ISDIR($mode & S_IFMT)) {
1779 } elsif (S_ISLNK($mode)) {
1781 } elsif (S_ISREG($mode)) {
1788 # convert file mode in octal to file type description string
1789 sub file_type_long {
1792 if ($mode !~ m/^[0-7]+$/) {
1798 if (S_ISGITLINK($mode)) {
1800 } elsif (S_ISDIR($mode & S_IFMT)) {
1802 } elsif (S_ISLNK($mode)) {
1804 } elsif (S_ISREG($mode)) {
1805 if ($mode & S_IXUSR) {
1806 return "executable";
1816 ## ----------------------------------------------------------------------
1817 ## functions returning short HTML fragments, or transforming HTML fragments
1818 ## which don't belong to other sections
1820 # format line of commit message.
1821 sub format_log_line_html {
1824 $line = esc_html($line, -nbsp=>1);
1825 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
1826 $cgi->a({-href => href(action=>"object", hash=>$1),
1827 -class => "text"}, $1);
1833 # format marker of refs pointing to given object
1835 # the destination action is chosen based on object type and current context:
1836 # - for annotated tags, we choose the tag view unless it's the current view
1837 # already, in which case we go to shortlog view
1838 # - for other refs, we keep the current view if we're in history, shortlog or
1839 # log view, and select shortlog otherwise
1840 sub format_ref_marker {
1841 my ($refs, $id) = @_;
1844 if (defined $refs->{$id}) {
1845 foreach my $ref (@{$refs->{$id}}) {
1846 # this code exploits the fact that non-lightweight tags are the
1847 # only indirect objects, and that they are the only objects for which
1848 # we want to use tag instead of shortlog as action
1849 my ($type, $name) = qw();
1850 my $indirect = ($ref =~ s/\^\{\}$//);
1851 # e.g. tags/v2.6.11 or heads/next
1852 if ($ref =~ m!^(.*?)s?/(.*)$!) {
1861 $class .= " indirect" if $indirect;
1863 my $dest_action = "shortlog";
1866 $dest_action = "tag" unless $action eq "tag";
1867 } elsif ($action =~ /^(history|(short)?log)$/) {
1868 $dest_action = $action;
1872 $dest .= "refs/" unless $ref =~ m!^refs/!;
1875 my $link = $cgi->a({
1877 action=>$dest_action,
1881 $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
1887 return ' <span class="refs">'. $markers . '</span>';
1893 # format, perhaps shortened and with markers, title line
1894 sub format_subject_html {
1895 my ($long, $short, $href, $extra) = @_;
1896 $extra = '' unless defined($extra);
1898 if (length($short) < length($long)) {
1899 $long =~ s/[[:cntrl:]]/?/g;
1900 return $cgi->a({-href => $href, -class => "list subject",
1901 -title => to_utf8($long)},
1902 esc_html($short)) . $extra;
1904 return $cgi->a({-href => $href, -class => "list subject"},
1905 esc_html($long)) . $extra;
1909 # Rather than recomputing the url for an email multiple times, we cache it
1910 # after the first hit. This gives a visible benefit in views where the avatar
1911 # for the same email is used repeatedly (e.g. shortlog).
1912 # The cache is shared by all avatar engines (currently gravatar only), which
1913 # are free to use it as preferred. Since only one avatar engine is used for any
1914 # given page, there's no risk for cache conflicts.
1915 our %avatar_cache = ();
1917 # Compute the picon url for a given email, by using the picon search service over at
1918 # http://www.cs.indiana.edu/picons/search.html
1920 my $email = lc shift;
1921 if (!$avatar_cache{$email}) {
1922 my ($user, $domain) = split('@', $email);
1923 $avatar_cache{$email} =
1924 "http://www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
1926 "users+domains+unknown/up/single";
1928 return $avatar_cache{$email};
1931 # Compute the gravatar url for a given email, if it's not in the cache already.
1932 # Gravatar stores only the part of the URL before the size, since that's the
1933 # one computationally more expensive. This also allows reuse of the cache for
1934 # different sizes (for this particular engine).
1936 my $email = lc shift;
1938 $avatar_cache{$email} ||=
1939 "http://www.gravatar.com/avatar/" .
1940 Digest::MD5::md5_hex($email) . "?s=";
1941 return $avatar_cache{$email} . $size;
1944 # Insert an avatar for the given $email at the given $size if the feature
1946 sub git_get_avatar {
1947 my ($email, %opts) = @_;
1948 my $pre_white = ($opts{-pad_before} ? " " : "");
1949 my $post_white = ($opts{-pad_after} ? " " : "");
1950 $opts{-size} ||= 'default';
1951 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
1953 if ($git_avatar eq 'gravatar') {
1954 $url = gravatar_url($email, $size);
1955 } elsif ($git_avatar eq 'picon') {
1956 $url = picon_url($email);
1958 # Other providers can be added by extending the if chain, defining $url
1959 # as needed. If no variant puts something in $url, we assume avatars
1960 # are completely disabled/unavailable.
1963 "<img width=\"$size\" " .
1964 "class=\"avatar\" " .
1965 "src=\"".esc_url($url)."\" " .
1973 sub format_search_author {
1974 my ($author, $searchtype, $displaytext) = @_;
1975 my $have_search = gitweb_check_feature('search');
1979 if ($searchtype eq 'author') {
1980 $performed = "authored";
1981 } elsif ($searchtype eq 'committer') {
1982 $performed = "committed";
1985 return $cgi->a({-href => href(action=>"search", hash=>$hash,
1986 searchtext=>$author,
1987 searchtype=>$searchtype), class=>"list",
1988 title=>"Search for commits $performed by $author"},
1992 return $displaytext;
1996 # format the author name of the given commit with the given tag
1997 # the author name is chopped and escaped according to the other
1998 # optional parameters (see chop_str).
1999 sub format_author_html {
2002 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2003 return "<$tag class=\"author\">" .
2004 format_search_author($co->{'author_name'}, "author",
2005 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2010 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2011 sub format_git_diff_header_line {
2013 my $diffinfo = shift;
2014 my ($from, $to) = @_;
2016 if ($diffinfo->{'nparents'}) {
2018 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2019 if ($to->{'href'}) {
2020 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2021 esc_path($to->{'file'}));
2022 } else { # file was deleted (no href)
2023 $line .= esc_path($to->{'file'});
2027 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2028 if ($from->{'href'}) {
2029 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2030 'a/' . esc_path($from->{'file'}));
2031 } else { # file was added (no href)
2032 $line .= 'a/' . esc_path($from->{'file'});
2035 if ($to->{'href'}) {
2036 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2037 'b/' . esc_path($to->{'file'}));
2038 } else { # file was deleted
2039 $line .= 'b/' . esc_path($to->{'file'});
2043 return "<div class=\"diff header\">$line</div>\n";
2046 # format extended diff header line, before patch itself
2047 sub format_extended_diff_header_line {
2049 my $diffinfo = shift;
2050 my ($from, $to) = @_;
2053 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2054 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2055 esc_path($from->{'file'}));
2057 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2058 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2059 esc_path($to->{'file'}));
2061 # match single <mode>
2062 if ($line =~ m/\s(\d{6})$/) {
2063 $line .= '<span class="info"> (' .
2064 file_type_long($1) .
2068 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2069 # can match only for combined diff
2071 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2072 if ($from->{'href'}[$i]) {
2073 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2075 substr($diffinfo->{'from_id'}[$i],0,7));
2080 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2083 if ($to->{'href'}) {
2084 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2085 substr($diffinfo->{'to_id'},0,7));
2090 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2091 # can match only for ordinary diff
2092 my ($from_link, $to_link);
2093 if ($from->{'href'}) {
2094 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2095 substr($diffinfo->{'from_id'},0,7));
2097 $from_link = '0' x 7;
2099 if ($to->{'href'}) {
2100 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2101 substr($diffinfo->{'to_id'},0,7));
2105 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2106 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2109 return $line . "<br/>\n";
2112 # format from-file/to-file diff header
2113 sub format_diff_from_to_header {
2114 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2119 #assert($line =~ m/^---/) if DEBUG;
2120 # no extra formatting for "^--- /dev/null"
2121 if (! $diffinfo->{'nparents'}) {
2122 # ordinary (single parent) diff
2123 if ($line =~ m!^--- "?a/!) {
2124 if ($from->{'href'}) {
2126 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2127 esc_path($from->{'file'}));
2130 esc_path($from->{'file'});
2133 $result .= qq!<div class="diff from_file">$line</div>\n!;
2136 # combined diff (merge commit)
2137 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2138 if ($from->{'href'}[$i]) {
2140 $cgi->a({-href=>href(action=>"blobdiff",
2141 hash_parent=>$diffinfo->{'from_id'}[$i],
2142 hash_parent_base=>$parents[$i],
2143 file_parent=>$from->{'file'}[$i],
2144 hash=>$diffinfo->{'to_id'},
2146 file_name=>$to->{'file'}),
2148 -title=>"diff" . ($i+1)},
2151 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2152 esc_path($from->{'file'}[$i]));
2154 $line = '--- /dev/null';
2156 $result .= qq!<div class="diff from_file">$line</div>\n!;
2161 #assert($line =~ m/^\+\+\+/) if DEBUG;
2162 # no extra formatting for "^+++ /dev/null"
2163 if ($line =~ m!^\+\+\+ "?b/!) {
2164 if ($to->{'href'}) {
2166 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2167 esc_path($to->{'file'}));
2170 esc_path($to->{'file'});
2173 $result .= qq!<div class="diff to_file">$line</div>\n!;
2178 # create note for patch simplified by combined diff
2179 sub format_diff_cc_simplified {
2180 my ($diffinfo, @parents) = @_;
2183 $result .= "<div class=\"diff header\">" .
2185 if (!is_deleted($diffinfo)) {
2186 $result .= $cgi->a({-href => href(action=>"blob",
2188 hash=>$diffinfo->{'to_id'},
2189 file_name=>$diffinfo->{'to_file'}),
2191 esc_path($diffinfo->{'to_file'}));
2193 $result .= esc_path($diffinfo->{'to_file'});
2195 $result .= "</div>\n" . # class="diff header"
2196 "<div class=\"diff nodifferences\">" .
2198 "</div>\n"; # class="diff nodifferences"
2203 # format patch (diff) line (not to be used for diff headers)
2204 sub format_diff_line {
2206 my ($from, $to) = @_;
2207 my $diff_class = "";
2211 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2213 my $prefix = substr($line, 0, scalar @{$from->{'href'}});
2214 if ($line =~ m/^\@{3}/) {
2215 $diff_class = " chunk_header";
2216 } elsif ($line =~ m/^\\/) {
2217 $diff_class = " incomplete";
2218 } elsif ($prefix =~ tr/+/+/) {
2219 $diff_class = " add";
2220 } elsif ($prefix =~ tr/-/-/) {
2221 $diff_class = " rem";
2224 # assume ordinary diff
2225 my $char = substr($line, 0, 1);
2227 $diff_class = " add";
2228 } elsif ($char eq '-') {
2229 $diff_class = " rem";
2230 } elsif ($char eq '@') {
2231 $diff_class = " chunk_header";
2232 } elsif ($char eq "\\") {
2233 $diff_class = " incomplete";
2236 $line = untabify($line);
2237 if ($from && $to && $line =~ m/^\@{2} /) {
2238 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2239 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2241 $from_lines = 0 unless defined $from_lines;
2242 $to_lines = 0 unless defined $to_lines;
2244 if ($from->{'href'}) {
2245 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2246 -class=>"list"}, $from_text);
2248 if ($to->{'href'}) {
2249 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2250 -class=>"list"}, $to_text);
2252 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2253 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2254 return "<div class=\"diff$diff_class\">$line</div>\n";
2255 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2256 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2257 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2259 @from_text = split(' ', $ranges);
2260 for (my $i = 0; $i < @from_text; ++$i) {
2261 ($from_start[$i], $from_nlines[$i]) =
2262 (split(',', substr($from_text[$i], 1)), 0);
2265 $to_text = pop @from_text;
2266 $to_start = pop @from_start;
2267 $to_nlines = pop @from_nlines;
2269 $line = "<span class=\"chunk_info\">$prefix ";
2270 for (my $i = 0; $i < @from_text; ++$i) {
2271 if ($from->{'href'}[$i]) {
2272 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2273 -class=>"list"}, $from_text[$i]);
2275 $line .= $from_text[$i];
2279 if ($to->{'href'}) {
2280 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2281 -class=>"list"}, $to_text);
2285 $line .= " $prefix</span>" .
2286 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2287 return "<div class=\"diff$diff_class\">$line</div>\n";
2289 return "<div class=\"diff$diff_class\">" . esc_html($line, -nbsp=>1) . "</div>\n";
2292 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2293 # linked. Pass the hash of the tree/commit to snapshot.
2294 sub format_snapshot_links {
2296 my $num_fmts = @snapshot_fmts;
2297 if ($num_fmts > 1) {
2298 # A parenthesized list of links bearing format names.
2299 # e.g. "snapshot (_tar.gz_ _zip_)"
2300 return "snapshot (" . join(' ', map
2307 }, $known_snapshot_formats{$_}{'display'})
2308 , @snapshot_fmts) . ")";
2309 } elsif ($num_fmts == 1) {
2310 # A single "snapshot" link whose tooltip bears the format name.
2312 my ($fmt) = @snapshot_fmts;
2318 snapshot_format=>$fmt
2320 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2322 } else { # $num_fmts == 0
2327 ## ......................................................................
2328 ## functions returning values to be passed, perhaps after some
2329 ## transformation, to other functions; e.g. returning arguments to href()
2331 # returns hash to be passed to href to generate gitweb URL
2332 # in -title key it returns description of link
2334 my $format = shift || 'Atom';
2335 my %res = (action => lc($format));
2337 # feed links are possible only for project views
2338 return unless (defined $project);
2339 # some views should link to OPML, or to generic project feed,
2340 # or don't have specific feed yet (so they should use generic)
2341 return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
2344 # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
2345 # from tag links; this also makes possible to detect branch links
2346 if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
2347 (defined $hash && $hash =~ m!^refs/heads/(.*)$!)) {
2350 # find log type for feed description (title)
2352 if (defined $file_name) {
2353 $type = "history of $file_name";
2354 $type .= "/" if ($action eq 'tree');
2355 $type .= " on '$branch'" if (defined $branch);
2357 $type = "log of $branch" if (defined $branch);
2360 $res{-title} = $type;
2361 $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
2362 $res{'file_name'} = $file_name;
2367 ## ----------------------------------------------------------------------
2368 ## git utility subroutines, invoking git commands
2370 # returns path to the core git executable and the --git-dir parameter as list
2372 $number_of_git_cmds++;
2373 return $GIT, '--git-dir='.$git_dir;
2376 # quote the given arguments for passing them to the shell
2377 # quote_command("command", "arg 1", "arg with ' and ! characters")
2378 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2379 # Try to avoid using this function wherever possible.
2382 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2385 # get HEAD ref of given project as hash
2386 sub git_get_head_hash {
2387 return git_get_full_hash(shift, 'HEAD');
2390 sub git_get_full_hash {
2391 return git_get_hash(@_);
2394 sub git_get_short_hash {
2395 return git_get_hash(@_, '--short=7');
2399 my ($project, $hash, @options) = @_;
2400 my $o_git_dir = $git_dir;
2402 $git_dir = "$projectroot/$project";
2403 if (open my $fd, '-|', git_cmd(), 'rev-parse',
2404 '--verify', '-q', @options, $hash) {
2406 chomp $retval if defined $retval;
2409 if (defined $o_git_dir) {
2410 $git_dir = $o_git_dir;
2415 # get type of given object
2419 open my $fd, "-|", git_cmd(), "cat-file", '-t', $hash or return;
2421 close $fd or return;
2426 # repository configuration
2427 our $config_file = '';
2430 # store multiple values for single key as anonymous array reference
2431 # single values stored directly in the hash, not as [ <value> ]
2432 sub hash_set_multi {
2433 my ($hash, $key, $value) = @_;
2435 if (!exists $hash->{$key}) {
2436 $hash->{$key} = $value;
2437 } elsif (!ref $hash->{$key}) {
2438 $hash->{$key} = [ $hash->{$key}, $value ];
2440 push @{$hash->{$key}}, $value;
2444 # return hash of git project configuration
2445 # optionally limited to some section, e.g. 'gitweb'
2446 sub git_parse_project_config {
2447 my $section_regexp = shift;
2452 open my $fh, "-|", git_cmd(), "config", '-z', '-l',
2455 while (my $keyval = <$fh>) {
2457 my ($key, $value) = split(/\n/, $keyval, 2);
2459 hash_set_multi(\%config, $key, $value)
2460 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2467 # convert config value to boolean: 'true' or 'false'
2468 # no value, number > 0, 'true' and 'yes' values are true
2469 # rest of values are treated as false (never as error)
2470 sub config_to_bool {
2473 return 1 if !defined $val; # section.key
2475 # strip leading and trailing whitespace
2479 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2480 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2483 # convert config value to simple decimal number
2484 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2485 # to be multiplied by 1024, 1048576, or 1073741824
2489 # strip leading and trailing whitespace
2493 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2495 # unknown unit is treated as 1
2496 return $num * ($unit eq 'g' ? 1073741824 :
2497 $unit eq 'm' ? 1048576 :
2498 $unit eq 'k' ? 1024 : 1);
2503 # convert config value to array reference, if needed
2504 sub config_to_multi {
2507 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2510 sub git_get_project_config {
2511 my ($key, $type) = @_;
2513 return unless defined $git_dir;
2516 return unless ($key);
2517 $key =~ s/^gitweb\.//;
2518 return if ($key =~ m/\W/);
2521 if (defined $type) {
2524 unless ($type eq 'bool' || $type eq 'int');
2528 if (!defined $config_file ||
2529 $config_file ne "$git_dir/config") {
2530 %config = git_parse_project_config('gitweb');
2531 $config_file = "$git_dir/config";
2534 # check if config variable (key) exists
2535 return unless exists $config{"gitweb.$key"};
2538 if (!defined $type) {
2539 return $config{"gitweb.$key"};
2540 } elsif ($type eq 'bool') {
2541 # backward compatibility: 'git config --bool' returns true/false
2542 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
2543 } elsif ($type eq 'int') {
2544 return config_to_int($config{"gitweb.$key"});
2546 return $config{"gitweb.$key"};
2549 # get hash of given path at given ref
2550 sub git_get_hash_by_path {
2552 my $path = shift || return undef;
2557 open my $fd, "-|", git_cmd(), "ls-tree", $base, "--", $path
2558 or die_error(500, "Open git-ls-tree failed");
2560 close $fd or return undef;
2562 if (!defined $line) {
2563 # there is no tree or hash given by $path at $base
2567 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
2568 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
2569 if (defined $type && $type ne $2) {
2570 # type doesn't match
2576 # get path of entry with given hash at given tree-ish (ref)
2577 # used to get 'from' filename for combined diff (merge commit) for renames
2578 sub git_get_path_by_hash {
2579 my $base = shift || return;
2580 my $hash = shift || return;
2584 open my $fd, "-|", git_cmd(), "ls-tree", '-r', '-t', '-z', $base
2586 while (my $line = <$fd>) {
2589 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
2590 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
2591 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
2600 ## ......................................................................
2601 ## git utility functions, directly accessing git repository
2603 # get the value of config variable either from file named as the variable
2604 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
2605 # configuration variable in the repository config file.
2606 sub git_get_file_or_project_config {
2607 my ($path, $name) = @_;
2609 $git_dir = "$projectroot/$path";
2610 open my $fd, '<', "$git_dir/$name"
2611 or return git_get_project_config($name);
2614 if (defined $conf) {
2620 sub git_get_project_description {
2622 return git_get_file_or_project_config($path, 'description');
2625 sub git_get_project_category {
2627 return git_get_file_or_project_config($path, 'category');
2631 # supported formats:
2632 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
2633 # - if its contents is a number, use it as tag weight,
2634 # - otherwise add a tag with weight 1
2635 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
2636 # the same value multiple times increases tag weight
2637 # * `gitweb.ctag' multi-valued repo config variable
2638 sub git_get_project_ctags {
2639 my $project = shift;
2642 $git_dir = "$projectroot/$project";
2643 if (opendir my $dh, "$git_dir/ctags") {
2644 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
2645 foreach my $tagfile (@files) {
2646 open my $ct, '<', $tagfile
2652 (my $ctag = $tagfile) =~ s#.*/##;
2653 if ($val =~ /^\d+$/) {
2654 $ctags->{$ctag} = $val;
2656 $ctags->{$ctag} = 1;
2661 } elsif (open my $fh, '<', "$git_dir/ctags") {
2662 while (my $line = <$fh>) {
2664 $ctags->{$line}++ if $line;
2669 my $taglist = config_to_multi(git_get_project_config('ctag'));
2670 foreach my $tag (@$taglist) {
2678 # return hash, where keys are content tags ('ctags'),
2679 # and values are sum of weights of given tag in every project
2680 sub git_gather_all_ctags {
2681 my $projects = shift;
2684 foreach my $p (@$projects) {
2685 foreach my $ct (keys %{$p->{'ctags'}}) {
2686 $ctags->{$ct} += $p->{'ctags'}->{$ct};
2693 sub git_populate_project_tagcloud {
2696 # First, merge different-cased tags; tags vote on casing
2698 foreach (keys %$ctags) {
2699 $ctags_lc{lc $_}->{count} += $ctags->{$_};
2700 if (not $ctags_lc{lc $_}->{topcount}
2701 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
2702 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
2703 $ctags_lc{lc $_}->{topname} = $_;
2708 my $matched = $cgi->param('by_tag');
2709 if (eval { require HTML::TagCloud; 1; }) {
2710 $cloud = HTML::TagCloud->new;
2711 foreach my $ctag (sort keys %ctags_lc) {
2712 # Pad the title with spaces so that the cloud looks
2714 my $title = esc_html($ctags_lc{$ctag}->{topname});
2715 $title =~ s/ / /g;
2716 $title =~ s/^/ /g;
2717 $title =~ s/$/ /g;
2718 if (defined $matched && $matched eq $ctag) {
2719 $title = qq(<span class="match">$title</span>);
2721 $cloud->add($title, href(project=>undef, ctag=>$ctag),
2722 $ctags_lc{$ctag}->{count});
2726 foreach my $ctag (keys %ctags_lc) {
2727 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
2728 if (defined $matched && $matched eq $ctag) {
2729 $title = qq(<span class="match">$title</span>);
2731 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
2732 $cloud->{$ctag}{ctag} =
2733 $cgi->a({-href=>href(project=>undef, ctag=>$ctag)}, $title);
2739 sub git_show_project_tagcloud {
2740 my ($cloud, $count) = @_;
2741 if (ref $cloud eq 'HTML::TagCloud') {
2742 return $cloud->html_and_css($count);
2744 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
2746 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
2748 $cloud->{$_}->{'ctag'}
2749 } splice(@tags, 0, $count)) .
2754 sub git_get_project_url_list {
2757 $git_dir = "$projectroot/$path";
2758 open my $fd, '<', "$git_dir/cloneurl"
2759 or return wantarray ?
2760 @{ config_to_multi(git_get_project_config('url')) } :
2761 config_to_multi(git_get_project_config('url'));
2762 my @git_project_url_list = map { chomp; $_ } <$fd>;
2765 return wantarray ? @git_project_url_list : \@git_project_url_list;
2768 sub git_get_projects_list {
2769 my $filter = shift || '';
2772 $filter =~ s/\.git$//;
2774 if (-d $projects_list) {
2775 # search in directory
2776 my $dir = $projects_list;
2777 # remove the trailing "/"
2779 my $pfxlen = length("$projects_list");
2780 my $pfxdepth = ($projects_list =~ tr!/!!);
2781 # when filtering, search only given subdirectory
2788 follow_fast => 1, # follow symbolic links
2789 follow_skip => 2, # ignore duplicates
2790 dangling_symlinks => 0, # ignore dangling symlinks, silently
2793 our $project_maxdepth;
2795 # skip project-list toplevel, if we get it.
2796 return if (m!^[/.]$!);
2797 # only directories can be git repositories
2798 return unless (-d $_);
2799 # don't traverse too deep (Find is super slow on os x)
2800 # $project_maxdepth excludes depth of $projectroot
2801 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
2802 $File::Find::prune = 1;
2806 my $path = substr($File::Find::name, $pfxlen + 1);
2807 # we check related file in $projectroot
2808 if (check_export_ok("$projectroot/$path")) {
2809 push @list, { path => $path };
2810 $File::Find::prune = 1;
2815 } elsif (-f $projects_list) {
2816 # read from file(url-encoded):
2817 # 'git%2Fgit.git Linus+Torvalds'
2818 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2819 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2820 open my $fd, '<', $projects_list or return;
2822 while (my $line = <$fd>) {
2824 my ($path, $owner) = split ' ', $line;
2825 $path = unescape($path);
2826 $owner = unescape($owner);
2827 if (!defined $path) {
2830 # if $filter is rpovided, check if $path begins with $filter
2831 if ($filter && $path !~ m!^\Q$filter\E/!) {
2834 if (check_export_ok("$projectroot/$path")) {
2837 owner => to_utf8($owner),
2847 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
2848 # as side effects it sets 'forks' field to list of forks for forked projects
2849 sub filter_forks_from_projects_list {
2850 my $projects = shift;
2852 my %trie; # prefix tree of directories (path components)
2853 # generate trie out of those directories that might contain forks
2854 foreach my $pr (@$projects) {
2855 my $path = $pr->{'path'};
2856 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
2857 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
2858 next unless ($path); # skip '.git' repository: tests, git-instaweb
2859 next unless (-d $path); # containing directory exists
2860 $pr->{'forks'} = []; # there can be 0 or more forks of project
2863 my @dirs = split('/', $path);
2864 # walk the trie, until either runs out of components or out of trie
2866 while (scalar @dirs &&
2867 exists($ref->{$dirs[0]})) {
2868 $ref = $ref->{shift @dirs};
2870 # create rest of trie structure from rest of components
2871 foreach my $dir (@dirs) {
2872 $ref = $ref->{$dir} = {};
2874 # create end marker, store $pr as a data
2875 $ref->{''} = $pr if (!exists $ref->{''});
2878 # filter out forks, by finding shortest prefix match for paths
2881 foreach my $pr (@$projects) {
2885 foreach my $dir (split('/', $pr->{'path'})) {
2886 if (exists $ref->{''}) {
2887 # found [shortest] prefix, is a fork - skip it
2888 push @{$ref->{''}{'forks'}}, $pr;
2891 if (!exists $ref->{$dir}) {
2892 # not in trie, cannot have prefix, not a fork
2893 push @filtered, $pr;
2896 # If the dir is there, we just walk one step down the trie.
2897 $ref = $ref->{$dir};
2899 # we ran out of trie
2900 # (shouldn't happen: it's either no match, or end marker)
2901 push @filtered, $pr;
2907 # note: fill_project_list_info must be run first,
2908 # for 'descr_long' and 'ctags' to be filled
2909 sub search_projects_list {
2910 my ($projlist, %opts) = @_;
2911 my $tagfilter = $opts{'tagfilter'};
2912 my $searchtext = $opts{'searchtext'};
2915 unless ($tagfilter || $searchtext);
2919 foreach my $pr (@$projlist) {
2922 next unless ref($pr->{'ctags'}) eq 'HASH';
2924 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
2929 $pr->{'path'} =~ /$searchtext/ ||
2930 $pr->{'descr_long'} =~ /$searchtext/;
2933 push @projects, $pr;
2939 our $gitweb_project_owner = undef;
2940 sub git_get_project_list_from_file {
2942 return if (defined $gitweb_project_owner);
2944 $gitweb_project_owner = {};
2945 # read from file (url-encoded):
2946 # 'git%2Fgit.git Linus+Torvalds'
2947 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
2948 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
2949 if (-f $projects_list) {
2950 open(my $fd, '<', $projects_list);
2951 while (my $line = <$fd>) {
2953 my ($pr, $ow) = split ' ', $line;
2954 $pr = unescape($pr);
2955 $ow = unescape($ow);
2956 $gitweb_project_owner->{$pr} = to_utf8($ow);
2962 sub git_get_project_owner {
2963 my $project = shift;
2966 return undef unless $project;
2967 $git_dir = "$projectroot/$project";
2969 if (!defined $gitweb_project_owner) {
2970 git_get_project_list_from_file();
2973 if (exists $gitweb_project_owner->{$project}) {
2974 $owner = $gitweb_project_owner->{$project};
2976 if (!defined $owner){
2977 $owner = git_get_project_config('owner');
2979 if (!defined $owner) {
2980 $owner = get_file_owner("$git_dir");
2986 sub git_get_last_activity {
2990 $git_dir = "$projectroot/$path";
2991 open($fd, "-|", git_cmd(), 'for-each-ref',
2992 '--format=%(committer)',
2993 '--sort=-committerdate',
2995 'refs/heads') or return;
2996 my $most_recent = <$fd>;
2997 close $fd or return;
2998 if (defined $most_recent &&
2999 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3001 my $age = time - $timestamp;
3002 return ($age, age_string($age));
3004 return (undef, undef);
3007 # Implementation note: when a single remote is wanted, we cannot use 'git
3008 # remote show -n' because that command always work (assuming it's a remote URL
3009 # if it's not defined), and we cannot use 'git remote show' because that would
3010 # try to make a network roundtrip. So the only way to find if that particular
3011 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3012 # and when we find what we want.
3013 sub git_get_remotes_list {
3017 open my $fd, '-|' , git_cmd(), 'remote', '-v';
3019 while (my $remote = <$fd>) {
3021 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3022 next if $wanted and not $remote eq $wanted;
3023 my ($url, $key) = ($1, $2);
3025 $remotes{$remote} ||= { 'heads' => () };
3026 $remotes{$remote}{$key} = $url;
3028 close $fd or return;
3029 return wantarray ? %remotes : \%remotes;
3032 # Takes a hash of remotes as first parameter and fills it by adding the
3033 # available remote heads for each of the indicated remotes.
3034 sub fill_remote_heads {
3035 my $remotes = shift;
3036 my @heads = map { "remotes/$_" } keys %$remotes;
3037 my @remoteheads = git_get_heads_list(undef, @heads);
3038 foreach my $remote (keys %$remotes) {
3039 $remotes->{$remote}{'heads'} = [ grep {
3040 $_->{'name'} =~ s!^$remote/!!
3045 sub git_get_references {
3046 my $type = shift || "";
3048 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3049 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3050 open my $fd, "-|", git_cmd(), "show-ref", "--dereference",
3051 ($type ? ("--", "refs/$type") : ()) # use -- <pattern> if $type
3054 while (my $line = <$fd>) {
3056 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3057 if (defined $refs{$1}) {
3058 push @{$refs{$1}}, $2;
3064 close $fd or return;
3068 sub git_get_rev_name_tags {
3069 my $hash = shift || return undef;
3071 open my $fd, "-|", git_cmd(), "name-rev", "--tags", $hash
3073 my $name_rev = <$fd>;
3076 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3079 # catches also '$hash undefined' output
3084 ## ----------------------------------------------------------------------
3085 ## parse to hash functions
3089 my $tz = shift || "-0000";
3092 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3093 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3094 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3095 $date{'hour'} = $hour;
3096 $date{'minute'} = $min;
3097 $date{'mday'} = $mday;
3098 $date{'day'} = $days[$wday];
3099 $date{'month'} = $months[$mon];
3100 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3101 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3102 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3103 $mday, $months[$mon], $hour ,$min;
3104 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3105 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3107 my ($tz_sign, $tz_hour, $tz_min) =
3108 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3109 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3110 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3111 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3112 $date{'hour_local'} = $hour;
3113 $date{'minute_local'} = $min;
3114 $date{'tz_local'} = $tz;
3115 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3116 1900+$year, $mon+1, $mday,
3117 $hour, $min, $sec, $tz);
3126 open my $fd, "-|", git_cmd(), "cat-file", "tag", $tag_id or return;
3127 $tag{'id'} = $tag_id;
3128 while (my $line = <$fd>) {
3130 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3131 $tag{'object'} = $1;
3132 } elsif ($line =~ m/^type (.+)$/) {
3134 } elsif ($line =~ m/^tag (.+)$/) {
3136 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3137 $tag{'author'} = $1;
3138 $tag{'author_epoch'} = $2;
3139 $tag{'author_tz'} = $3;
3140 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3141 $tag{'author_name'} = $1;
3142 $tag{'author_email'} = $2;
3144 $tag{'author_name'} = $tag{'author'};
3146 } elsif ($line =~ m/--BEGIN/) {
3147 push @comment, $line;
3149 } elsif ($line eq "") {
3153 push @comment, <$fd>;
3154 $tag{'comment'} = \@comment;
3155 close $fd or return;
3156 if (!defined $tag{'name'}) {
3162 sub parse_commit_text {
3163 my ($commit_text, $withparents) = @_;
3164 my @commit_lines = split '\n', $commit_text;
3167 pop @commit_lines; # Remove '\0'
3169 if (! @commit_lines) {
3173 my $header = shift @commit_lines;
3174 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3177 ($co{'id'}, my @parents) = split ' ', $header;
3178 while (my $line = shift @commit_lines) {
3179 last if $line eq "\n";
3180 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3182 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3184 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3185 $co{'author'} = to_utf8($1);
3186 $co{'author_epoch'} = $2;
3187 $co{'author_tz'} = $3;
3188 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3189 $co{'author_name'} = $1;
3190 $co{'author_email'} = $2;
3192 $co{'author_name'} = $co{'author'};
3194 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3195 $co{'committer'} = to_utf8($1);
3196 $co{'committer_epoch'} = $2;
3197 $co{'committer_tz'} = $3;
3198 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3199 $co{'committer_name'} = $1;
3200 $co{'committer_email'} = $2;
3202 $co{'committer_name'} = $co{'committer'};
3206 if (!defined $co{'tree'}) {
3209 $co{'parents'} = \@parents;
3210 $co{'parent'} = $parents[0];
3212 foreach my $title (@commit_lines) {
3215 $co{'title'} = chop_str($title, 80, 5);
3216 # remove leading stuff of merges to make the interesting part visible
3217 if (length($title) > 50) {
3218 $title =~ s/^Automatic //;
3219 $title =~ s/^merge (of|with) /Merge ... /i;
3220 if (length($title) > 50) {
3221 $title =~ s/(http|rsync):\/\///;
3223 if (length($title) > 50) {
3224 $title =~ s/(master|www|rsync)\.//;
3226 if (length($title) > 50) {
3227 $title =~ s/kernel.org:?//;
3229 if (length($title) > 50) {
3230 $title =~ s/\/pub\/scm//;
3233 $co{'title_short'} = chop_str($title, 50, 5);
3237 if (! defined $co{'title'} || $co{'title'} eq "") {
3238 $co{'title'} = $co{'title_short'} = '(no commit message)';
3240 # remove added spaces
3241 foreach my $line (@commit_lines) {
3244 $co{'comment'} = \@commit_lines;
3246 my $age = time - $co{'committer_epoch'};
3248 $co{'age_string'} = age_string($age);
3249 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3250 if ($age > 60*60*24*7*2) {
3251 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3252 $co{'age_string_age'} = $co{'age_string'};
3254 $co{'age_string_date'} = $co{'age_string'};
3255 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3261 my ($commit_id) = @_;
3266 open my $fd, "-|", git_cmd(), "rev-list",
3272 or die_error(500, "Open git-rev-list failed");
3273 %co = parse_commit_text(<$fd>, 1);
3280 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3288 open my $fd, "-|", git_cmd(), "rev-list",
3291 ("--max-count=" . $maxcount),
3292 ("--skip=" . $skip),
3296 ($filename ? ($filename) : ())
3297 or die_error(500, "Open git-rev-list failed");
3298 while (my $line = <$fd>) {
3299 my %co = parse_commit_text($line);
3304 return wantarray ? @cos : \@cos;
3307 # parse line of git-diff-tree "raw" output
3308 sub parse_difftree_raw_line {
3312 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3313 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3314 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3315 $res{'from_mode'} = $1;
3316 $res{'to_mode'} = $2;
3317 $res{'from_id'} = $3;
3319 $res{'status'} = $5;
3320 $res{'similarity'} = $6;
3321 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3322 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3324 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3327 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3328 # combined diff (for merge commit)
3329 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3330 $res{'nparents'} = length($1);
3331 $res{'from_mode'} = [ split(' ', $2) ];
3332 $res{'to_mode'} = pop @{$res{'from_mode'}};
3333 $res{'from_id'} = [ split(' ', $3) ];
3334 $res{'to_id'} = pop @{$res{'from_id'}};
3335 $res{'status'} = [ split('', $4) ];
3336 $res{'to_file'} = unquote($5);
3338 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3339 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3340 $res{'commit'} = $1;
3343 return wantarray ? %res : \%res;
3346 # wrapper: return parsed line of git-diff-tree "raw" output
3347 # (the argument might be raw line, or parsed info)
3348 sub parsed_difftree_line {
3349 my $line_or_ref = shift;
3351 if (ref($line_or_ref) eq "HASH") {
3352 # pre-parsed (or generated by hand)
3353 return $line_or_ref;
3355 return parse_difftree_raw_line($line_or_ref);
3359 # parse line of git-ls-tree output
3360 sub parse_ls_tree_line {
3366 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3367 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3376 $res{'name'} = unquote($5);
3379 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3380 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3388 $res{'name'} = unquote($4);
3392 return wantarray ? %res : \%res;
3395 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3396 sub parse_from_to_diffinfo {
3397 my ($diffinfo, $from, $to, @parents) = @_;
3399 if ($diffinfo->{'nparents'}) {
3401 $from->{'file'} = [];
3402 $from->{'href'} = [];
3403 fill_from_file_info($diffinfo, @parents)
3404 unless exists $diffinfo->{'from_file'};
3405 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3406 $from->{'file'}[$i] =
3407 defined $diffinfo->{'from_file'}[$i] ?
3408 $diffinfo->{'from_file'}[$i] :
3409 $diffinfo->{'to_file'};
3410 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3411 $from->{'href'}[$i] = href(action=>"blob",
3412 hash_base=>$parents[$i],
3413 hash=>$diffinfo->{'from_id'}[$i],
3414 file_name=>$from->{'file'}[$i]);
3416 $from->{'href'}[$i] = undef;
3420 # ordinary (not combined) diff
3421 $from->{'file'} = $diffinfo->{'from_file'};
3422 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3423 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3424 hash=>$diffinfo->{'from_id'},
3425 file_name=>$from->{'file'});
3427 delete $from->{'href'};
3431 $to->{'file'} = $diffinfo->{'to_file'};
3432 if (!is_deleted($diffinfo)) { # file exists in result
3433 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3434 hash=>$diffinfo->{'to_id'},
3435 file_name=>$to->{'file'});
3437 delete $to->{'href'};
3441 ## ......................................................................
3442 ## parse to array of hashes functions
3444 sub git_get_heads_list {
3445 my ($limit, @classes) = @_;
3446 @classes = ('heads') unless @classes;
3447 my @patterns = map { "refs/$_" } @classes;
3450 open my $fd, '-|', git_cmd(), 'for-each-ref',
3451 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3452 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3455 while (my $line = <$fd>) {
3459 my ($refinfo, $committerinfo) = split(/\0/, $line);
3460 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3461 my ($committer, $epoch, $tz) =
3462 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3463 $ref_item{'fullname'} = $name;
3464 $name =~ s!^refs/(?:head|remote)s/!!;
3466 $ref_item{'name'} = $name;
3467 $ref_item{'id'} = $hash;
3468 $ref_item{'title'} = $title || '(no commit message)';
3469 $ref_item{'epoch'} = $epoch;
3471 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3473 $ref_item{'age'} = "unknown";
3476 push @headslist, \%ref_item;
3480 return wantarray ? @headslist : \@headslist;
3483 sub git_get_tags_list {
3487 open my $fd, '-|', git_cmd(), 'for-each-ref',
3488 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3489 '--format=%(objectname) %(objecttype) %(refname) '.
3490 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3493 while (my $line = <$fd>) {
3497 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3498 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3499 my ($creator, $epoch, $tz) =
3500 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3501 $ref_item{'fullname'} = $name;
3502 $name =~ s!^refs/tags/!!;
3504 $ref_item{'type'} = $type;
3505 $ref_item{'id'} = $id;
3506 $ref_item{'name'} = $name;
3507 if ($type eq "tag") {
3508 $ref_item{'subject'} = $title;
3509 $ref_item{'reftype'} = $reftype;
3510 $ref_item{'refid'} = $refid;
3512 $ref_item{'reftype'} = $type;
3513 $ref_item{'refid'} = $id;
3516 if ($type eq "tag" || $type eq "commit") {
3517 $ref_item{'epoch'} = $epoch;
3519 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3521 $ref_item{'age'} = "unknown";
3525 push @tagslist, \%ref_item;
3529 return wantarray ? @tagslist : \@tagslist;
3532 ## ----------------------------------------------------------------------
3533 ## filesystem-related functions
3535 sub get_file_owner {
3538 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
3539 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
3540 if (!defined $gcos) {
3544 $owner =~ s/[,;].*$//;
3545 return to_utf8($owner);
3548 # assume that file exists
3550 my $filename = shift;
3552 open my $fd, '<', $filename;
3553 print map { to_utf8($_) } <$fd>;
3557 ## ......................................................................
3558 ## mimetype related functions
3560 sub mimetype_guess_file {
3561 my $filename = shift;
3562 my $mimemap = shift;
3563 -r $mimemap or return undef;
3566 open(my $mh, '<', $mimemap) or return undef;
3568 next if m/^#/; # skip comments
3569 my ($mimetype, @exts) = split(/\s+/);
3570 foreach my $ext (@exts) {
3571 $mimemap{$ext} = $mimetype;
3576 $filename =~ /\.([^.]*)$/;
3577 return $mimemap{$1};
3580 sub mimetype_guess {
3581 my $filename = shift;
3583 $filename =~ /\./ or return undef;
3585 if ($mimetypes_file) {
3586 my $file = $mimetypes_file;
3587 if ($file !~ m!^/!) { # if it is relative path
3588 # it is relative to project
3589 $file = "$projectroot/$project/$file";
3591 $mime = mimetype_guess_file($filename, $file);
3593 $mime ||= mimetype_guess_file($filename, '/etc/mime.types');
3599 my $filename = shift;
3602 my $mime = mimetype_guess($filename);
3603 $mime and return $mime;
3607 return $default_blob_plain_mimetype unless $fd;
3610 return 'text/plain';
3611 } elsif (! $filename) {
3612 return 'application/octet-stream';
3613 } elsif ($filename =~ m/\.png$/i) {
3615 } elsif ($filename =~ m/\.gif$/i) {
3617 } elsif ($filename =~ m/\.jpe?g$/i) {
3618 return 'image/jpeg';
3620 return 'application/octet-stream';
3624 sub blob_contenttype {
3625 my ($fd, $file_name, $type) = @_;
3627 $type ||= blob_mimetype($fd, $file_name);
3628 if ($type eq 'text/plain' && defined $default_text_plain_charset) {
3629 $type .= "; charset=$default_text_plain_charset";
3635 # guess file syntax for syntax highlighting; return undef if no highlighting
3636 # the name of syntax can (in the future) depend on syntax highlighter used
3637 sub guess_file_syntax {
3638 my ($highlight, $mimetype, $file_name) = @_;
3639 return undef unless ($highlight && defined $file_name);
3640 my $basename = basename($file_name, '.in');
3641 return $highlight_basename{$basename}
3642 if exists $highlight_basename{$basename};
3644 $basename =~ /\.([^.]*)$/;
3645 my $ext = $1 or return undef;
3646 return $highlight_ext{$ext}
3647 if exists $highlight_ext{$ext};
3652 # run highlighter and return FD of its output,
3653 # or return original FD if no highlighting
3654 sub run_highlighter {
3655 my ($fd, $highlight, $syntax) = @_;
3656 return $fd unless ($highlight && defined $syntax);
3659 open $fd, quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
3660 quote_command($highlight_bin).
3661 " --replace-tabs=8 --fragment --syntax $syntax |"
3662 or die_error(500, "Couldn't open file or run syntax highlighter");
3666 ## ======================================================================
3667 ## functions printing HTML: header, footer, error page
3669 sub get_page_title {
3670 my $title = to_utf8($site_name);
3672 return $title unless (defined $project);
3673 $title .= " - " . to_utf8($project);
3675 return $title unless (defined $action);
3676 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
3678 return $title unless (defined $file_name);
3679 $title .= " - " . esc_path($file_name);
3680 if ($action eq "tree" && $file_name !~ m|/$|) {
3687 sub get_content_type_html {
3688 # require explicit support from the UA if we are to send the page as
3689 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
3690 # we have to do this because MSIE sometimes globs '*/*', pretending to
3691 # support xhtml+xml but choking when it gets what it asked for.
3692 if (defined $cgi->http('HTTP_ACCEPT') &&
3693 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
3694 $cgi->Accept('application/xhtml+xml') != 0) {
3695 return 'application/xhtml+xml';
3701 sub print_feed_meta {
3702 if (defined $project) {
3703 my %href_params = get_feed_info();
3704 if (!exists $href_params{'-title'}) {
3705 $href_params{'-title'} = 'log';
3708 foreach my $format (qw(RSS Atom)) {
3709 my $type = lc($format);
3711 '-rel' => 'alternate',
3712 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
3713 '-type' => "application/$type+xml"
3716 $href_params{'action'} = $type;
3717 $link_attr{'-href'} = href(%href_params);
3719 "rel=\"$link_attr{'-rel'}\" ".
3720 "title=\"$link_attr{'-title'}\" ".
3721 "href=\"$link_attr{'-href'}\" ".
3722 "type=\"$link_attr{'-type'}\" ".
3725 $href_params{'extra_options'} = '--no-merges';
3726 $link_attr{'-href'} = href(%href_params);
3727 $link_attr{'-title'} .= ' (no merges)';
3729 "rel=\"$link_attr{'-rel'}\" ".
3730 "title=\"$link_attr{'-title'}\" ".
3731 "href=\"$link_attr{'-href'}\" ".
3732 "type=\"$link_attr{'-type'}\" ".
3737 printf('<link rel="alternate" title="%s projects list" '.
3738 'href="%s" type="text/plain; charset=utf-8" />'."\n",
3739 esc_attr($site_name), href(project=>undef, action=>"project_index"));
3740 printf('<link rel="alternate" title="%s projects feeds" '.
3741 'href="%s" type="text/x-opml" />'."\n",
3742 esc_attr($site_name), href(project=>undef, action=>"opml"));
3746 sub print_header_links {
3749 # print out each stylesheet that exist, providing backwards capability
3750 # for those people who defined $stylesheet in a config file
3751 if (defined $stylesheet) {
3752 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
3754 foreach my $stylesheet (@stylesheets) {
3755 next unless $stylesheet;
3756 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
3760 if ($status eq '200 OK');
3761 if (defined $favicon) {
3762 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
3766 sub print_nav_breadcrumbs {
3769 print $cgi->a({-href => esc_url($home_link)}, $home_link_str) . " / ";
3770 if (defined $project) {
3771 print $cgi->a({-href => href(action=>"summary")}, esc_html($project));
3772 if (defined $action) {
3773 my $action_print = $action ;
3774 if (defined $opts{-action_extra}) {
3775 $action_print = $cgi->a({-href => href(action=>$action)},
3778 print " / $action_print";
3780 if (defined $opts{-action_extra}) {
3781 print " / $opts{-action_extra}";
3787 sub print_search_form {
3788 if (!defined $searchtext) {
3792 if (defined $hash_base) {
3793 $search_hash = $hash_base;
3794 } elsif (defined $hash) {
3795 $search_hash = $hash;
3797 $search_hash = "HEAD";
3799 my $action = $my_uri;
3800 my $use_pathinfo = gitweb_check_feature('pathinfo');
3801 if ($use_pathinfo) {
3802 $action .= "/".esc_url($project);
3804 print $cgi->startform(-method => "get", -action => $action) .
3805 "<div class=\"search\">\n" .
3807 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
3808 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
3809 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
3810 $cgi->popup_menu(-name => 'st', -default => 'commit',
3811 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
3812 $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
3814 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
3815 "<span title=\"Extended regular expression\">" .
3816 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
3817 -checked => $search_use_regexp) .
3820 $cgi->end_form() . "\n";
3823 sub git_header_html {
3824 my $status = shift || "200 OK";
3825 my $expires = shift;
3828 my $title = get_page_title();
3829 my $content_type = get_content_type_html();
3830 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
3831 -status=> $status, -expires => $expires)
3832 unless ($opts{'-no_http_header'});
3833 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
3835 <?xml version="1.0" encoding="utf-8"?>
3836 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3837 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
3838 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
3839 <!-- git core binaries version $git_version -->
3841 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
3842 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
3843 <meta name="robots" content="index, nofollow"/>
3844 <title>$title</title>
3846 # the stylesheet, favicon etc urls won't work correctly with path_info
3847 # unless we set the appropriate base URL
3848 if ($ENV{'PATH_INFO'}) {
3849 print "<base href=\"".esc_url($base_url)."\" />\n";
3851 print_header_links($status);
3855 if (defined $site_header && -f $site_header) {
3856 insert_file($site_header);
3859 print "<div class=\"page_header\">\n";
3860 if (defined $logo) {
3861 print $cgi->a({-href => esc_url($logo_url),
3862 -title => $logo_label},
3863 $cgi->img({-src => esc_url($logo),
3864 -width => 72, -height => 27,
3866 -class => "logo"}));
3868 print_nav_breadcrumbs(%opts);
3871 my $have_search = gitweb_check_feature('search');
3872 if (defined $project && $have_search) {
3873 print_search_form();
3877 sub git_footer_html {
3878 my $feed_class = 'rss_logo';
3880 print "<div class=\"page_footer\">\n";
3881 if (defined $project) {
3882 my $descr = git_get_project_description($project);
3883 if (defined $descr) {
3884 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
3887 my %href_params = get_feed_info();
3888 if (!%href_params) {
3889 $feed_class .= ' generic';
3891 $href_params{'-title'} ||= 'log';
3893 foreach my $format (qw(RSS Atom)) {
3894 $href_params{'action'} = lc($format);
3895 print $cgi->a({-href => href(%href_params),
3896 -title => "$href_params{'-title'} $format feed",
3897 -class => $feed_class}, $format)."\n";
3901 print $cgi->a({-href => href(project=>undef, action=>"opml"),
3902 -class => $feed_class}, "OPML") . " ";
3903 print $cgi->a({-href => href(project=>undef, action=>"project_index"),
3904 -class => $feed_class}, "TXT") . "\n";
3906 print "</div>\n"; # class="page_footer"
3908 if (defined $t0 && gitweb_check_feature('timed')) {
3909 print "<div id=\"generating_info\">\n";
3910 print 'This page took '.
3911 '<span id="generating_time" class="time_span">'.
3912 tv_interval($t0, [ gettimeofday() ]).
3915 '<span id="generating_cmd">'.
3916 $number_of_git_cmds.
3917 '</span> git commands '.
3919 print "</div>\n"; # class="page_footer"
3922 if (defined $site_footer && -f $site_footer) {
3923 insert_file($site_footer);
3926 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
3927 if (defined $action &&
3928 $action eq 'blame_incremental') {
3929 print qq!<script type="text/javascript">\n!.
3930 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
3931 qq! "!. href() .qq!");\n!.
3934 my ($jstimezone, $tz_cookie, $datetime_class) =
3935 gitweb_get_feature('javascript-timezone');
3937 print qq!<script type="text/javascript">\n!.
3938 qq!window.onload = function () {\n!;
3939 if (gitweb_check_feature('javascript-actions')) {
3940 print qq! fixLinks();\n!;
3942 if ($jstimezone && $tz_cookie && $datetime_class) {
3943 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
3944 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
3954 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
3955 # Example: die_error(404, 'Hash not found')
3956 # By convention, use the following status codes (as defined in RFC 2616):
3957 # 400: Invalid or missing CGI parameters, or
3958 # requested object exists but has wrong type.
3959 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
3960 # this server or project.
3961 # 404: Requested object/revision/project doesn't exist.
3962 # 500: The server isn't configured properly, or
3963 # an internal error occurred (e.g. failed assertions caused by bugs), or
3964 # an unknown error occurred (e.g. the git binary died unexpectedly).
3965 # 503: The server is currently unavailable (because it is overloaded,
3966 # or down for maintenance). Generally, this is a temporary state.
3968 my $status = shift || 500;
3969 my $error = esc_html(shift) || "Internal Server Error";
3973 my %http_responses = (
3974 400 => '400 Bad Request',
3975 403 => '403 Forbidden',
3976 404 => '404 Not Found',
3977 500 => '500 Internal Server Error',
3978 503 => '503 Service Unavailable',
3980 git_header_html($http_responses{$status}, undef, %opts);
3982 <div class="page_body">
3987 if (defined $extra) {
3995 unless ($opts{'-error_handler'});
3998 ## ----------------------------------------------------------------------
3999 ## functions printing or outputting HTML: navigation
4001 sub git_print_page_nav {
4002 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4003 $extra = '' if !defined $extra; # pager or formats
4005 my @navs = qw(summary shortlog log commit commitdiff tree);
4007 @navs = grep { $_ ne $suppress } @navs;
4010 my %arg = map { $_ => {action=>$_} } @navs;
4011 if (defined $head) {
4012 for (qw(commit commitdiff)) {
4013 $arg{$_}{'hash'} = $head;
4015 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4016 for (qw(shortlog log)) {
4017 $arg{$_}{'hash'} = $head;
4022 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4023 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4025 my @actions = gitweb_get_feature('actions');
4028 'n' => $project, # project name
4029 'f' => $git_dir, # project path within filesystem
4030 'h' => $treehead || '', # current hash ('h' parameter)
4031 'b' => $treebase || '', # hash base ('hb' parameter)
4034 my ($label, $link, $pos) = splice(@actions,0,3);
4036 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4038 $link =~ s/%([%nfhb])/$repl{$1}/g;
4039 $arg{$label}{'_href'} = $link;
4042 print "<div class=\"page_nav\">\n" .
4044 map { $_ eq $current ?
4045 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4047 print "<br/>\n$extra<br/>\n" .
4051 # returns a submenu for the nagivation of the refs views (tags, heads,
4052 # remotes) with the current view disabled and the remotes view only
4053 # available if the feature is enabled
4054 sub format_ref_views {
4056 my @ref_views = qw{tags heads};
4057 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4058 return join " | ", map {
4059 $_ eq $current ? $_ :
4060 $cgi->a({-href => href(action=>$_)}, $_)
4064 sub format_paging_nav {
4065 my ($action, $page, $has_next_link) = @_;
4071 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4073 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4074 -accesskey => "p", -title => "Alt-p"}, "prev");
4076 $paging_nav .= "first ⋅ prev";
4079 if ($has_next_link) {
4080 $paging_nav .= " ⋅ " .
4081 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4082 -accesskey => "n", -title => "Alt-n"}, "next");
4084 $paging_nav .= " ⋅ next";
4090 ## ......................................................................
4091 ## functions printing or outputting HTML: div
4093 sub git_print_header_div {
4094 my ($action, $title, $hash, $hash_base) = @_;
4097 $args{'action'} = $action;
4098 $args{'hash'} = $hash if $hash;
4099 $args{'hash_base'} = $hash_base if $hash_base;
4101 print "<div class=\"header\">\n" .
4102 $cgi->a({-href => href(%args), -class => "title"},
4103 $title ? $title : $action) .
4107 sub format_repo_url {
4108 my ($name, $url) = @_;
4109 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4112 # Group output by placing it in a DIV element and adding a header.
4113 # Options for start_div() can be provided by passing a hash reference as the
4114 # first parameter to the function.
4115 # Options to git_print_header_div() can be provided by passing an array
4116 # reference. This must follow the options to start_div if they are present.
4117 # The content can be a scalar, which is output as-is, a scalar reference, which
4118 # is output after html escaping, an IO handle passed either as *handle or
4119 # *handle{IO}, or a function reference. In the latter case all following
4120 # parameters will be taken as argument to the content function call.
4121 sub git_print_section {
4122 my ($div_args, $header_args, $content);
4124 if (ref($arg) eq 'HASH') {
4128 if (ref($arg) eq 'ARRAY') {
4129 $header_args = $arg;
4134 print $cgi->start_div($div_args);
4135 git_print_header_div(@$header_args);
4137 if (ref($content) eq 'CODE') {
4139 } elsif (ref($content) eq 'SCALAR') {
4140 print esc_html($$content);
4141 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4143 } elsif (!ref($content) && defined($content)) {
4147 print $cgi->end_div;
4150 sub format_timestamp_html {
4152 my $strtime = $date->{'rfc2822'};
4154 my (undef, undef, $datetime_class) =
4155 gitweb_get_feature('javascript-timezone');
4156 if ($datetime_class) {
4157 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4160 my $localtime_format = '(%02d:%02d %s)';
4161 if ($date->{'hour_local'} < 6) {
4162 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4165 sprintf($localtime_format,
4166 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4171 # Outputs the author name and date in long form
4172 sub git_print_authorship {
4175 my $tag = $opts{-tag} || 'div';
4176 my $author = $co->{'author_name'};
4178 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4179 print "<$tag class=\"author_date\">" .
4180 format_search_author($author, "author", esc_html($author)) .
4181 " [".format_timestamp_html(\%ad)."]".
4182 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4186 # Outputs table rows containing the full author or committer information,
4187 # in the format expected for 'commit' view (& similar).
4188 # Parameters are a commit hash reference, followed by the list of people
4189 # to output information for. If the list is empty it defaults to both
4190 # author and committer.
4191 sub git_print_authorship_rows {
4193 # too bad we can't use @people = @_ || ('author', 'committer')
4195 @people = ('author', 'committer') unless @people;
4196 foreach my $who (@people) {
4197 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4198 print "<tr><td>$who</td><td>" .
4199 format_search_author($co->{"${who}_name"}, $who,
4200 esc_html($co->{"${who}_name"})) . " " .
4201 format_search_author($co->{"${who}_email"}, $who,
4202 esc_html("<" . $co->{"${who}_email"} . ">")) .
4203 "</td><td rowspan=\"2\">" .
4204 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4208 format_timestamp_html(\%wd) .
4214 sub git_print_page_path {
4220 print "<div class=\"page_path\">";
4221 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4222 -title => 'tree root'}, to_utf8("[$project]"));
4224 if (defined $name) {
4225 my @dirname = split '/', $name;
4226 my $basename = pop @dirname;
4229 foreach my $dir (@dirname) {
4230 $fullname .= ($fullname ? '/' : '') . $dir;
4231 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4233 -title => $fullname}, esc_path($dir));
4236 if (defined $type && $type eq 'blob') {
4237 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4239 -title => $name}, esc_path($basename));
4240 } elsif (defined $type && $type eq 'tree') {
4241 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4243 -title => $name}, esc_path($basename));
4246 print esc_path($basename);
4249 print "<br/></div>\n";
4256 if ($opts{'-remove_title'}) {
4257 # remove title, i.e. first line of log
4260 # remove leading empty lines
4261 while (defined $log->[0] && $log->[0] eq "") {
4268 foreach my $line (@$log) {
4269 if ($line =~ m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i) {
4272 if (! $opts{'-remove_signoff'}) {
4273 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4276 # remove signoff lines
4283 # print only one empty line
4284 # do not print empty line after signoff
4286 next if ($empty || $signoff);
4292 print format_log_line_html($line) . "<br/>\n";
4295 if ($opts{'-final_empty_line'}) {
4296 # end with single empty line
4297 print "<br/>\n" unless $empty;
4301 # return link target (what link points to)
4302 sub git_get_link_target {
4307 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
4311 $link_target = <$fd>;
4316 return $link_target;
4319 # given link target, and the directory (basedir) the link is in,
4320 # return target of link relative to top directory (top tree);
4321 # return undef if it is not possible (including absolute links).
4322 sub normalize_link_target {
4323 my ($link_target, $basedir) = @_;
4325 # absolute symlinks (beginning with '/') cannot be normalized
4326 return if (substr($link_target, 0, 1) eq '/');
4328 # normalize link target to path from top (root) tree (dir)
4331 $path = $basedir . '/' . $link_target;
4333 # we are in top (root) tree (dir)
4334 $path = $link_target;
4337 # remove //, /./, and /../
4339 foreach my $part (split('/', $path)) {
4340 # discard '.' and ''
4341 next if (!$part || $part eq '.');
4343 if ($part eq '..') {
4347 # link leads outside repository (outside top dir)
4351 push @path_parts, $part;
4354 $path = join('/', @path_parts);
4359 # print tree entry (row of git_tree), but without encompassing <tr> element
4360 sub git_print_tree_entry {
4361 my ($t, $basedir, $hash_base, $have_blame) = @_;
4364 $base_key{'hash_base'} = $hash_base if defined $hash_base;
4366 # The format of a table row is: mode list link. Where mode is
4367 # the mode of the entry, list is the name of the entry, an href,
4368 # and link is the action links of the entry.
4370 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
4371 if (exists $t->{'size'}) {
4372 print "<td class=\"size\">$t->{'size'}</td>\n";
4374 if ($t->{'type'} eq "blob") {
4375 print "<td class=\"list\">" .
4376 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4377 file_name=>"$basedir$t->{'name'}", %base_key),
4378 -class => "list"}, esc_path($t->{'name'}));
4379 if (S_ISLNK(oct $t->{'mode'})) {
4380 my $link_target = git_get_link_target($t->{'hash'});
4382 my $norm_target = normalize_link_target($link_target, $basedir);
4383 if (defined $norm_target) {
4385 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
4386 file_name=>$norm_target),
4387 -title => $norm_target}, esc_path($link_target));
4389 print " -> " . esc_path($link_target);
4394 print "<td class=\"link\">";
4395 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
4396 file_name=>"$basedir$t->{'name'}", %base_key)},
4400 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
4401 file_name=>"$basedir$t->{'name'}", %base_key)},
4404 if (defined $hash_base) {
4406 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4407 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
4411 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
4412 file_name=>"$basedir$t->{'name'}")},
4416 } elsif ($t->{'type'} eq "tree") {
4417 print "<td class=\"list\">";
4418 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4419 file_name=>"$basedir$t->{'name'}",
4421 esc_path($t->{'name'}));
4423 print "<td class=\"link\">";
4424 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
4425 file_name=>"$basedir$t->{'name'}",
4428 if (defined $hash_base) {
4430 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
4431 file_name=>"$basedir$t->{'name'}")},
4436 # unknown object: we can only present history for it
4437 # (this includes 'commit' object, i.e. submodule support)
4438 print "<td class=\"list\">" .
4439 esc_path($t->{'name'}) .
4441 print "<td class=\"link\">";
4442 if (defined $hash_base) {
4443 print $cgi->a({-href => href(action=>"history",
4444 hash_base=>$hash_base,
4445 file_name=>"$basedir$t->{'name'}")},
4452 ## ......................................................................
4453 ## functions printing large fragments of HTML
4455 # get pre-image filenames for merge (combined) diff
4456 sub fill_from_file_info {
4457 my ($diff, @parents) = @_;
4459 $diff->{'from_file'} = [ ];
4460 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
4461 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4462 if ($diff->{'status'}[$i] eq 'R' ||
4463 $diff->{'status'}[$i] eq 'C') {
4464 $diff->{'from_file'}[$i] =
4465 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
4472 # is current raw difftree line of file deletion
4474 my $diffinfo = shift;
4476 return $diffinfo->{'to_id'} eq ('0' x 40);
4479 # does patch correspond to [previous] difftree raw line
4480 # $diffinfo - hashref of parsed raw diff format
4481 # $patchinfo - hashref of parsed patch diff format
4482 # (the same keys as in $diffinfo)
4483 sub is_patch_split {
4484 my ($diffinfo, $patchinfo) = @_;
4486 return defined $diffinfo && defined $patchinfo
4487 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
4491 sub git_difftree_body {
4492 my ($difftree, $hash, @parents) = @_;
4493 my ($parent) = $parents[0];
4494 my $have_blame = gitweb_check_feature('blame');
4495 print "<div class=\"list_head\">\n";
4496 if ($#{$difftree} > 10) {
4497 print(($#{$difftree} + 1) . " files changed:\n");
4501 print "<table class=\"" .
4502 (@parents > 1 ? "combined " : "") .
4505 # header only for combined diff in 'commitdiff' view
4506 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
4509 print "<thead><tr>\n" .
4510 "<th></th><th></th>\n"; # filename, patchN link
4511 for (my $i = 0; $i < @parents; $i++) {
4512 my $par = $parents[$i];
4514 $cgi->a({-href => href(action=>"commitdiff",
4515 hash=>$hash, hash_parent=>$par),
4516 -title => 'commitdiff to parent number ' .
4517 ($i+1) . ': ' . substr($par,0,7)},
4521 print "</tr></thead>\n<tbody>\n";
4526 foreach my $line (@{$difftree}) {
4527 my $diff = parsed_difftree_line($line);
4530 print "<tr class=\"dark\">\n";
4532 print "<tr class=\"light\">\n";
4536 if (exists $diff->{'nparents'}) { # combined diff
4538 fill_from_file_info($diff, @parents)
4539 unless exists $diff->{'from_file'};
4541 if (!is_deleted($diff)) {
4542 # file exists in the result (child) commit
4544 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4545 file_name=>$diff->{'to_file'},
4547 -class => "list"}, esc_path($diff->{'to_file'})) .
4551 esc_path($diff->{'to_file'}) .
4555 if ($action eq 'commitdiff') {
4558 print "<td class=\"link\">" .
4559 $cgi->a({-href => href(-anchor=>"patch$patchno")},
4565 my $has_history = 0;
4566 my $not_deleted = 0;
4567 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
4568 my $hash_parent = $parents[$i];
4569 my $from_hash = $diff->{'from_id'}[$i];
4570 my $from_path = $diff->{'from_file'}[$i];
4571 my $status = $diff->{'status'}[$i];
4573 $has_history ||= ($status ne 'A');
4574 $not_deleted ||= ($status ne 'D');
4576 if ($status eq 'A') {
4577 print "<td class=\"link\" align=\"right\"> | </td>\n";
4578 } elsif ($status eq 'D') {
4579 print "<td class=\"link\">" .
4580 $cgi->a({-href => href(action=>"blob",
4583 file_name=>$from_path)},
4587 if ($diff->{'to_id'} eq $from_hash) {
4588 print "<td class=\"link nochange\">";
4590 print "<td class=\"link\">";
4592 print $cgi->a({-href => href(action=>"blobdiff",
4593 hash=>$diff->{'to_id'},
4594 hash_parent=>$from_hash,
4596 hash_parent_base=>$hash_parent,
4597 file_name=>$diff->{'to_file'},
4598 file_parent=>$from_path)},
4604 print "<td class=\"link\">";
4606 print $cgi->a({-href => href(action=>"blob",
4607 hash=>$diff->{'to_id'},
4608 file_name=>$diff->{'to_file'},
4611 print " | " if ($has_history);
4614 print $cgi->a({-href => href(action=>"history",
4615 file_name=>$diff->{'to_file'},
4622 next; # instead of 'else' clause, to avoid extra indent
4624 # else ordinary diff
4626 my ($to_mode_oct, $to_mode_str, $to_file_type);
4627 my ($from_mode_oct, $from_mode_str, $from_file_type);
4628 if ($diff->{'to_mode'} ne ('0' x 6)) {
4629 $to_mode_oct = oct $diff->{'to_mode'};
4630 if (S_ISREG($to_mode_oct)) { # only for regular file
4631 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
4633 $to_file_type = file_type($diff->{'to_mode'});
4635 if ($diff->{'from_mode'} ne ('0' x 6)) {
4636 $from_mode_oct = oct $diff->{'from_mode'};
4637 if (S_ISREG($from_mode_oct)) { # only for regular file
4638 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
4640 $from_file_type = file_type($diff->{'from_mode'});
4643 if ($diff->{'status'} eq "A") { # created
4644 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
4645 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
4646 $mode_chng .= "]</span>";
4648 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4649 hash_base=>$hash, file_name=>$diff->{'file'}),
4650 -class => "list"}, esc_path($diff->{'file'}));
4652 print "<td>$mode_chng</td>\n";
4653 print "<td class=\"link\">";
4654 if ($action eq 'commitdiff') {
4657 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4661 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4662 hash_base=>$hash, file_name=>$diff->{'file'})},
4666 } elsif ($diff->{'status'} eq "D") { # deleted
4667 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
4669 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4670 hash_base=>$parent, file_name=>$diff->{'file'}),
4671 -class => "list"}, esc_path($diff->{'file'}));
4673 print "<td>$mode_chng</td>\n";
4674 print "<td class=\"link\">";
4675 if ($action eq 'commitdiff') {
4678 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4682 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
4683 hash_base=>$parent, file_name=>$diff->{'file'})},
4686 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
4687 file_name=>$diff->{'file'})},
4690 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
4691 file_name=>$diff->{'file'})},
4695 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
4696 my $mode_chnge = "";
4697 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4698 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
4699 if ($from_file_type ne $to_file_type) {
4700 $mode_chnge .= " from $from_file_type to $to_file_type";
4702 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
4703 if ($from_mode_str && $to_mode_str) {
4704 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
4705 } elsif ($to_mode_str) {
4706 $mode_chnge .= " mode: $to_mode_str";
4709 $mode_chnge .= "]</span>\n";
4712 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4713 hash_base=>$hash, file_name=>$diff->{'file'}),
4714 -class => "list"}, esc_path($diff->{'file'}));
4716 print "<td>$mode_chnge</td>\n";
4717 print "<td class=\"link\">";
4718 if ($action eq 'commitdiff') {
4721 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4724 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4725 # "commit" view and modified file (not onlu mode changed)
4726 print $cgi->a({-href => href(action=>"blobdiff",
4727 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4728 hash_base=>$hash, hash_parent_base=>$parent,
4729 file_name=>$diff->{'file'})},
4733 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4734 hash_base=>$hash, file_name=>$diff->{'file'})},
4737 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4738 file_name=>$diff->{'file'})},
4741 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4742 file_name=>$diff->{'file'})},
4746 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
4747 my %status_name = ('R' => 'moved', 'C' => 'copied');
4748 my $nstatus = $status_name{$diff->{'status'}};
4750 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
4751 # mode also for directories, so we cannot use $to_mode_str
4752 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
4755 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
4756 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
4757 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
4758 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
4759 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
4760 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
4761 -class => "list"}, esc_path($diff->{'from_file'})) .
4762 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
4763 "<td class=\"link\">";
4764 if ($action eq 'commitdiff') {
4767 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
4770 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
4771 # "commit" view and modified file (not only pure rename or copy)
4772 print $cgi->a({-href => href(action=>"blobdiff",
4773 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
4774 hash_base=>$hash, hash_parent_base=>$parent,
4775 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
4779 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
4780 hash_base=>$parent, file_name=>$diff->{'to_file'})},
4783 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
4784 file_name=>$diff->{'to_file'})},
4787 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
4788 file_name=>$diff->{'to_file'})},
4792 } # we should not encounter Unmerged (U) or Unknown (X) status
4795 print "</tbody>" if $has_header;
4799 sub git_patchset_body {
4800 my ($fd, $difftree, $hash, @hash_parents) = @_;
4801 my ($hash_parent) = $hash_parents[0];
4803 my $is_combined = (@hash_parents > 1);
4805 my $patch_number = 0;
4811 print "<div class=\"patchset\">\n";
4813 # skip to first patch
4814 while ($patch_line = <$fd>) {
4817 last if ($patch_line =~ m/^diff /);
4821 while ($patch_line) {
4823 # parse "git diff" header line
4824 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
4825 # $1 is from_name, which we do not use
4826 $to_name = unquote($2);
4827 $to_name =~ s!^b/!!;
4828 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
4829 # $1 is 'cc' or 'combined', which we do not use
4830 $to_name = unquote($2);
4835 # check if current patch belong to current raw line
4836 # and parse raw git-diff line if needed
4837 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
4838 # this is continuation of a split patch
4839 print "<div class=\"patch cont\">\n";
4841 # advance raw git-diff output if needed
4842 $patch_idx++ if defined $diffinfo;
4844 # read and prepare patch information
4845 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4847 # compact combined diff output can have some patches skipped
4848 # find which patch (using pathname of result) we are at now;
4850 while ($to_name ne $diffinfo->{'to_file'}) {
4851 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4852 format_diff_cc_simplified($diffinfo, @hash_parents) .
4853 "</div>\n"; # class="patch"
4858 last if $patch_idx > $#$difftree;
4859 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4863 # modifies %from, %to hashes
4864 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
4866 # this is first patch for raw difftree line with $patch_idx index
4867 # we index @$difftree array from 0, but number patches from 1
4868 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
4872 #assert($patch_line =~ m/^diff /) if DEBUG;
4873 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
4875 # print "git diff" header
4876 print format_git_diff_header_line($patch_line, $diffinfo,
4879 # print extended diff header
4880 print "<div class=\"diff extended_header\">\n";
4882 while ($patch_line = <$fd>) {
4885 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
4887 print format_extended_diff_header_line($patch_line, $diffinfo,
4890 print "</div>\n"; # class="diff extended_header"
4892 # from-file/to-file diff header
4893 if (! $patch_line) {
4894 print "</div>\n"; # class="patch"
4897 next PATCH if ($patch_line =~ m/^diff /);
4898 #assert($patch_line =~ m/^---/) if DEBUG;
4900 my $last_patch_line = $patch_line;
4901 $patch_line = <$fd>;
4903 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
4905 print format_diff_from_to_header($last_patch_line, $patch_line,
4906 $diffinfo, \%from, \%to,
4911 while ($patch_line = <$fd>) {
4914 next PATCH if ($patch_line =~ m/^diff /);
4916 print format_diff_line($patch_line, \%from, \%to);
4920 print "</div>\n"; # class="patch"
4923 # for compact combined (--cc) format, with chunk and patch simplification
4924 # the patchset might be empty, but there might be unprocessed raw lines
4925 for (++$patch_idx if $patch_number > 0;
4926 $patch_idx < @$difftree;
4928 # read and prepare patch information
4929 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
4931 # generate anchor for "patch" links in difftree / whatchanged part
4932 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
4933 format_diff_cc_simplified($diffinfo, @hash_parents) .
4934 "</div>\n"; # class="patch"
4939 if ($patch_number == 0) {
4940 if (@hash_parents > 1) {
4941 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
4943 print "<div class=\"diff nodifferences\">No differences found</div>\n";
4947 print "</div>\n"; # class="patchset"
4950 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4952 # fills project list info (age, description, owner, category, forks)
4953 # for each project in the list, removing invalid projects from
4955 # NOTE: modifies $projlist, but does not remove entries from it
4956 sub fill_project_list_info {
4957 my $projlist = shift;
4960 my $show_ctags = gitweb_check_feature('ctags');
4962 foreach my $pr (@$projlist) {
4963 my (@activity) = git_get_last_activity($pr->{'path'});
4964 unless (@activity) {
4967 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
4968 if (!defined $pr->{'descr'}) {
4969 my $descr = git_get_project_description($pr->{'path'}) || "";
4970 $descr = to_utf8($descr);
4971 $pr->{'descr_long'} = $descr;
4972 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
4974 if (!defined $pr->{'owner'}) {
4975 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
4978 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
4980 if ($projects_list_group_categories && !defined $pr->{'category'}) {
4981 my $cat = git_get_project_category($pr->{'path'}) ||
4982 $project_list_default_category;
4983 $pr->{'category'} = to_utf8($cat);
4986 push @projects, $pr;
4992 sub sort_projects_list {
4993 my ($projlist, $order) = @_;
4997 project => { key => 'path', type => 'str' },
4998 descr => { key => 'descr_long', type => 'str' },
4999 owner => { key => 'owner', type => 'str' },
5000 age => { key => 'age', type => 'num' }
5002 my $oi = $order_info{$order};
5003 return @$projlist unless defined $oi;
5004 if ($oi->{'type'} eq 'str') {
5005 @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @$projlist;
5007 @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @$projlist;
5013 # returns a hash of categories, containing the list of project
5014 # belonging to each category
5015 sub build_projlist_by_category {
5016 my ($projlist, $from, $to) = @_;
5019 $from = 0 unless defined $from;
5020 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5022 for (my $i = $from; $i <= $to; $i++) {
5023 my $pr = $projlist->[$i];
5024 push @{$categories{ $pr->{'category'} }}, $pr;
5027 return wantarray ? %categories : \%categories;
5030 # print 'sort by' <th> element, generating 'sort by $name' replay link
5031 # if that order is not selected
5033 print format_sort_th(@_);
5036 sub format_sort_th {
5037 my ($name, $order, $header) = @_;
5039 $header ||= ucfirst($name);
5041 if ($order eq $name) {
5042 $sort_th .= "<th>$header</th>\n";
5044 $sort_th .= "<th>" .
5045 $cgi->a({-href => href(-replay=>1, order=>$name),
5046 -class => "header"}, $header) .
5053 sub git_project_list_rows {
5054 my ($projlist, $from, $to, $check_forks) = @_;
5056 $from = 0 unless defined $from;
5057 $to = $#$projlist if (!defined $to || $#$projlist < $to);
5060 for (my $i = $from; $i <= $to; $i++) {
5061 my $pr = $projlist->[$i];
5064 print "<tr class=\"dark\">\n";
5066 print "<tr class=\"light\">\n";
5072 if ($pr->{'forks'}) {
5073 my $nforks = scalar @{$pr->{'forks'}};
5075 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
5076 -title => "$nforks forks"}, "+");
5078 print $cgi->span({-title => "$nforks forks"}, "+");
5083 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5084 -class => "list"}, esc_html($pr->{'path'})) . "</td>\n" .
5085 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
5086 -class => "list", -title => $pr->{'descr_long'}},
5087 esc_html($pr->{'descr'})) . "</td>\n" .
5088 "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
5089 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
5090 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
5091 "<td class=\"link\">" .
5092 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
5093 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
5094 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
5095 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
5096 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
5102 sub git_project_list_body {
5103 # actually uses global variable $project
5104 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
5105 my @projects = @$projlist;
5107 my $check_forks = gitweb_check_feature('forks');
5108 my $show_ctags = gitweb_check_feature('ctags');
5109 my $tagfilter = $show_ctags ? $cgi->param('by_tag') : undef;
5110 $check_forks = undef
5111 if ($tagfilter || $searchtext);
5113 # filtering out forks before filling info allows to do less work
5114 @projects = filter_forks_from_projects_list(\@projects)
5116 @projects = fill_project_list_info(\@projects);
5117 # searching projects require filling to be run before it
5118 @projects = search_projects_list(\@projects,
5119 'searchtext' => $searchtext,
5120 'tagfilter' => $tagfilter)
5121 if ($tagfilter || $searchtext);
5123 $order ||= $default_projects_order;
5124 $from = 0 unless defined $from;
5125 $to = $#projects if (!defined $to || $#projects < $to);
5130 "<b>No such projects found</b><br />\n".
5131 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
5132 "</center>\n<br />\n";
5136 @projects = sort_projects_list(\@projects, $order);
5139 my $ctags = git_gather_all_ctags(\@projects);
5140 my $cloud = git_populate_project_tagcloud($ctags);
5141 print git_show_project_tagcloud($cloud, 64);
5144 print "<table class=\"project_list\">\n";
5145 unless ($no_header) {
5148 print "<th></th>\n";
5150 print_sort_th('project', $order, 'Project');
5151 print_sort_th('descr', $order, 'Description');
5152 print_sort_th('owner', $order, 'Owner');
5153 print_sort_th('age', $order, 'Last Change');
5154 print "<th></th>\n" . # for links
5158 if ($projects_list_group_categories) {
5159 # only display categories with projects in the $from-$to window
5160 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
5161 my %categories = build_projlist_by_category(\@projects, $from, $to);
5162 foreach my $cat (sort keys %categories) {
5163 unless ($cat eq "") {
5166 print "<td></td>\n";
5168 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
5172 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
5175 git_project_list_rows(\@projects, $from, $to, $check_forks);
5178 if (defined $extra) {
5181 print "<td></td>\n";
5183 print "<td colspan=\"5\">$extra</td>\n" .
5190 # uses global variable $project
5191 my ($commitlist, $from, $to, $refs, $extra) = @_;
5193 $from = 0 unless defined $from;
5194 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5196 for (my $i = 0; $i <= $to; $i++) {
5197 my %co = %{$commitlist->[$i]};
5199 my $commit = $co{'id'};
5200 my $ref = format_ref_marker($refs, $commit);
5201 git_print_header_div('commit',
5202 "<span class=\"age\">$co{'age_string'}</span>" .
5203 esc_html($co{'title'}) . $ref,
5205 print "<div class=\"title_text\">\n" .
5206 "<div class=\"log_link\">\n" .
5207 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
5209 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
5211 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
5214 git_print_authorship(\%co, -tag => 'span');
5215 print "<br/>\n</div>\n";
5217 print "<div class=\"log_body\">\n";
5218 git_print_log($co{'comment'}, -final_empty_line=> 1);
5222 print "<div class=\"page_nav\">\n";
5228 sub git_shortlog_body {
5229 # uses global variable $project
5230 my ($commitlist, $from, $to, $refs, $extra) = @_;
5232 $from = 0 unless defined $from;
5233 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5235 print "<table class=\"shortlog\">\n";
5237 for (my $i = $from; $i <= $to; $i++) {
5238 my %co = %{$commitlist->[$i]};
5239 my $commit = $co{'id'};
5240 my $ref = format_ref_marker($refs, $commit);
5242 print "<tr class=\"dark\">\n";
5244 print "<tr class=\"light\">\n";
5247 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
5248 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5249 format_author_html('td', \%co, 10) . "<td>";
5250 print format_subject_html($co{'title'}, $co{'title_short'},
5251 href(action=>"commit", hash=>$commit), $ref);
5253 "<td class=\"link\">" .
5254 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
5255 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
5256 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
5257 my $snapshot_links = format_snapshot_links($commit);
5258 if (defined $snapshot_links) {
5259 print " | " . $snapshot_links;
5264 if (defined $extra) {
5266 "<td colspan=\"4\">$extra</td>\n" .
5272 sub git_history_body {
5273 # Warning: assumes constant type (blob or tree) during history
5274 my ($commitlist, $from, $to, $refs, $extra,
5275 $file_name, $file_hash, $ftype) = @_;
5277 $from = 0 unless defined $from;
5278 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
5280 print "<table class=\"history\">\n";
5282 for (my $i = $from; $i <= $to; $i++) {
5283 my %co = %{$commitlist->[$i]};
5287 my $commit = $co{'id'};
5289 my $ref = format_ref_marker($refs, $commit);
5292 print "<tr class=\"dark\">\n";
5294 print "<tr class=\"light\">\n";
5297 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5298 # shortlog: format_author_html('td', \%co, 10)
5299 format_author_html('td', \%co, 15, 3) . "<td>";
5300 # originally git_history used chop_str($co{'title'}, 50)
5301 print format_subject_html($co{'title'}, $co{'title_short'},
5302 href(action=>"commit", hash=>$commit), $ref);
5304 "<td class=\"link\">" .
5305 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
5306 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
5308 if ($ftype eq 'blob') {
5309 my $blob_current = $file_hash;
5310 my $blob_parent = git_get_hash_by_path($commit, $file_name);
5311 if (defined $blob_current && defined $blob_parent &&
5312 $blob_current ne $blob_parent) {
5314 $cgi->a({-href => href(action=>"blobdiff",
5315 hash=>$blob_current, hash_parent=>$blob_parent,
5316 hash_base=>$hash_base, hash_parent_base=>$commit,
5317 file_name=>$file_name)},
5324 if (defined $extra) {
5326 "<td colspan=\"4\">$extra</td>\n" .
5333 # uses global variable $project
5334 my ($taglist, $from, $to, $extra) = @_;
5335 $from = 0 unless defined $from;
5336 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
5338 print "<table class=\"tags\">\n";
5340 for (my $i = $from; $i <= $to; $i++) {
5341 my $entry = $taglist->[$i];
5343 my $comment = $tag{'subject'};
5345 if (defined $comment) {
5346 $comment_short = chop_str($comment, 30, 5);
5349 print "<tr class=\"dark\">\n";
5351 print "<tr class=\"light\">\n";
5354 if (defined $tag{'age'}) {
5355 print "<td><i>$tag{'age'}</i></td>\n";
5357 print "<td></td>\n";
5360 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
5361 -class => "list name"}, esc_html($tag{'name'})) .
5364 if (defined $comment) {
5365 print format_subject_html($comment, $comment_short,
5366 href(action=>"tag", hash=>$tag{'id'}));
5369 "<td class=\"selflink\">";
5370 if ($tag{'type'} eq "tag") {
5371 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
5376 "<td class=\"link\">" . " | " .
5377 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
5378 if ($tag{'reftype'} eq "commit") {
5379 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
5380 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
5381 } elsif ($tag{'reftype'} eq "blob") {
5382 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
5387 if (defined $extra) {
5389 "<td colspan=\"5\">$extra</td>\n" .
5395 sub git_heads_body {
5396 # uses global variable $project
5397 my ($headlist, $head, $from, $to, $extra) = @_;
5398 $from = 0 unless defined $from;
5399 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
5401 print "<table class=\"heads\">\n";
5403 for (my $i = $from; $i <= $to; $i++) {
5404 my $entry = $headlist->[$i];
5406 my $curr = $ref{'id'} eq $head;
5408 print "<tr class=\"dark\">\n";
5410 print "<tr class=\"light\">\n";
5413 print "<td><i>$ref{'age'}</i></td>\n" .
5414 ($curr ? "<td class=\"current_head\">" : "<td>") .
5415 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
5416 -class => "list name"},esc_html($ref{'name'})) .
5418 "<td class=\"link\">" .
5419 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
5420 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
5421 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
5425 if (defined $extra) {
5427 "<td colspan=\"3\">$extra</td>\n" .
5433 # Display a single remote block
5434 sub git_remote_block {
5435 my ($remote, $rdata, $limit, $head) = @_;
5437 my $heads = $rdata->{'heads'};
5438 my $fetch = $rdata->{'fetch'};
5439 my $push = $rdata->{'push'};
5441 my $urls_table = "<table class=\"projects_list\">\n" ;
5443 if (defined $fetch) {
5444 if ($fetch eq $push) {
5445 $urls_table .= format_repo_url("URL", $fetch);
5447 $urls_table .= format_repo_url("Fetch URL", $fetch);
5448 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
5450 } elsif (defined $push) {
5451 $urls_table .= format_repo_url("Push URL", $push);
5453 $urls_table .= format_repo_url("", "No remote URL");
5456 $urls_table .= "</table>\n";
5459 if (defined $limit && $limit < @$heads) {
5460 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
5464 git_heads_body($heads, $head, 0, $limit, $dots);
5467 # Display a list of remote names with the respective fetch and push URLs
5468 sub git_remotes_list {
5469 my ($remotedata, $limit) = @_;
5470 print "<table class=\"heads\">\n";
5472 my @remotes = sort keys %$remotedata;
5474 my $limited = $limit && $limit < @remotes;
5476 $#remotes = $limit - 1 if $limited;
5478 while (my $remote = shift @remotes) {
5479 my $rdata = $remotedata->{$remote};
5480 my $fetch = $rdata->{'fetch'};
5481 my $push = $rdata->{'push'};
5483 print "<tr class=\"dark\">\n";
5485 print "<tr class=\"light\">\n";
5489 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
5490 -class=> "list name"},esc_html($remote)) .
5492 print "<td class=\"link\">" .
5493 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
5495 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
5503 "<td colspan=\"3\">" .
5504 $cgi->a({-href => href(action=>"remotes")}, "...") .
5505 "</td>\n" . "</tr>\n";
5511 # Display remote heads grouped by remote, unless there are too many
5512 # remotes, in which case we only display the remote names
5513 sub git_remotes_body {
5514 my ($remotedata, $limit, $head) = @_;
5515 if ($limit and $limit < keys %$remotedata) {
5516 git_remotes_list($remotedata, $limit);
5518 fill_remote_heads($remotedata);
5519 while (my ($remote, $rdata) = each %$remotedata) {
5520 git_print_section({-class=>"remote", -id=>$remote},
5521 ["remotes", $remote, $remote], sub {
5522 git_remote_block($remote, $rdata, $limit, $head);
5528 sub git_search_message {
5532 if ($searchtype eq 'commit') {
5533 $greptype = "--grep=";
5534 } elsif ($searchtype eq 'author') {
5535 $greptype = "--author=";
5536 } elsif ($searchtype eq 'committer') {
5537 $greptype = "--committer=";
5539 $greptype .= $searchtext;
5540 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
5541 $greptype, '--regexp-ignore-case',
5542 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
5544 my $paging_nav = '';
5547 $cgi->a({-href => href(-replay=>1, page=>undef)},
5550 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5551 -accesskey => "p", -title => "Alt-p"}, "prev");
5553 $paging_nav .= "first ⋅ prev";
5556 if ($#commitlist >= 100) {
5558 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5559 -accesskey => "n", -title => "Alt-n"}, "next");
5560 $paging_nav .= " ⋅ $next_link";
5562 $paging_nav .= " ⋅ next";
5567 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
5568 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5569 if ($page == 0 && !@commitlist) {
5570 print "<p>No match.</p>\n";
5572 git_search_grep_body(\@commitlist, 0, 99, $next_link);
5578 sub git_search_changes {
5582 open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
5583 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
5584 ($search_use_regexp ? '--pickaxe-regex' : ())
5585 or die_error(500, "Open git-log failed");
5589 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5590 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5592 print "<table class=\"pickaxe search\">\n";
5596 while (my $line = <$fd>) {
5600 my %set = parse_difftree_raw_line($line);
5601 if (defined $set{'commit'}) {
5602 # finish previous commit
5605 "<td class=\"link\">" .
5606 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
5609 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
5610 hash_base=>$co{'id'})},
5617 print "<tr class=\"dark\">\n";
5619 print "<tr class=\"light\">\n";
5622 %co = parse_commit($set{'commit'});
5623 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
5624 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5625 "<td><i>$author</i></td>\n" .
5627 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5628 -class => "list subject"},
5629 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5630 } elsif (defined $set{'to_id'}) {
5631 next if ($set{'to_id'} =~ m/^0{40}$/);
5633 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
5634 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
5636 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
5642 # finish last commit (warning: repetition!)
5645 "<td class=\"link\">" .
5646 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
5649 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
5650 hash_base=>$co{'id'})},
5661 sub git_search_files {
5665 open my $fd, "-|", git_cmd(), 'grep', '-n',
5666 $search_use_regexp ? ('-E', '-i') : '-F',
5667 $searchtext, $co{'tree'}
5668 or die_error(500, "Open git-grep failed");
5672 git_print_page_nav('','', $hash,$co{'tree'},$hash);
5673 git_print_header_div('commit', esc_html($co{'title'}), $hash);
5675 print "<table class=\"grep_search\">\n";
5679 while (my $line = <$fd>) {
5681 my ($file, $lno, $ltext, $binary);
5682 last if ($matches++ > 1000);
5683 if ($line =~ /^Binary file (.+) matches$/) {
5687 (undef, $file, $lno, $ltext) = split(/:/, $line, 4);
5689 if ($file ne $lastfile) {
5690 $lastfile and print "</td></tr>\n";
5692 print "<tr class=\"dark\">\n";
5694 print "<tr class=\"light\">\n";
5696 print "<td class=\"list\">".
5697 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5698 file_name=>"$file"),
5699 -class => "list"}, esc_path($file));
5700 print "</td><td>\n";
5704 print "<div class=\"binary\">Binary file</div>\n";
5706 $ltext = untabify($ltext);
5707 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
5708 $ltext = esc_html($1, -nbsp=>1);
5709 $ltext .= '<span class="match">';
5710 $ltext .= esc_html($2, -nbsp=>1);
5711 $ltext .= '</span>';
5712 $ltext .= esc_html($3, -nbsp=>1);
5714 $ltext = esc_html($ltext, -nbsp=>1);
5716 print "<div class=\"pre\">" .
5717 $cgi->a({-href => href(action=>"blob", hash=>$co{'hash'},
5718 file_name=>"$file").'#l'.$lno,
5719 -class => "linenr"}, sprintf('%4i', $lno))
5720 . ' ' . $ltext . "</div>\n";
5724 print "</td></tr>\n";
5725 if ($matches > 1000) {
5726 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
5729 print "<div class=\"diff nodifferences\">No matches found</div>\n";
5738 sub git_search_grep_body {
5739 my ($commitlist, $from, $to, $extra) = @_;
5740 $from = 0 unless defined $from;
5741 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
5743 print "<table class=\"commit_search\">\n";
5745 for (my $i = $from; $i <= $to; $i++) {
5746 my %co = %{$commitlist->[$i]};
5750 my $commit = $co{'id'};
5752 print "<tr class=\"dark\">\n";
5754 print "<tr class=\"light\">\n";
5757 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
5758 format_author_html('td', \%co, 15, 5) .
5760 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
5761 -class => "list subject"},
5762 chop_and_escape_str($co{'title'}, 50) . "<br/>");
5763 my $comment = $co{'comment'};
5764 foreach my $line (@$comment) {
5765 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
5766 my ($lead, $match, $trail) = ($1, $2, $3);
5767 $match = chop_str($match, 70, 5, 'center');
5768 my $contextlen = int((80 - length($match))/2);
5769 $contextlen = 30 if ($contextlen > 30);
5770 $lead = chop_str($lead, $contextlen, 10, 'left');
5771 $trail = chop_str($trail, $contextlen, 10, 'right');
5773 $lead = esc_html($lead);
5774 $match = esc_html($match);
5775 $trail = esc_html($trail);
5777 print "$lead<span class=\"match\">$match</span>$trail<br />";
5781 "<td class=\"link\">" .
5782 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
5784 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
5786 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
5790 if (defined $extra) {
5792 "<td colspan=\"3\">$extra</td>\n" .
5798 ## ======================================================================
5799 ## ======================================================================
5802 sub git_project_list {
5803 my $order = $input_params{'order'};
5804 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5805 die_error(400, "Unknown order parameter");
5808 my @list = git_get_projects_list();
5810 die_error(404, "No projects found");
5814 if (defined $home_text && -f $home_text) {
5815 print "<div class=\"index_include\">\n";
5816 insert_file($home_text);
5819 print $cgi->startform(-method => "get") .
5820 "<p class=\"projsearch\">Search:\n" .
5821 $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
5823 $cgi->end_form() . "\n";
5824 git_project_list_body(\@list, $order);
5829 my $order = $input_params{'order'};
5830 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
5831 die_error(400, "Unknown order parameter");
5834 my @list = git_get_projects_list($project);
5836 die_error(404, "No forks found");
5840 git_print_page_nav('','');
5841 git_print_header_div('summary', "$project forks");
5842 git_project_list_body(\@list, $order);
5846 sub git_project_index {
5847 my @projects = git_get_projects_list();
5849 die_error(404, "No projects found");
5853 -type => 'text/plain',
5854 -charset => 'utf-8',
5855 -content_disposition => 'inline; filename="index.aux"');
5857 foreach my $pr (@projects) {
5858 if (!exists $pr->{'owner'}) {
5859 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
5862 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
5863 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
5864 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5865 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
5869 print "$path $owner\n";
5874 my $descr = git_get_project_description($project) || "none";
5875 my %co = parse_commit("HEAD");
5876 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
5877 my $head = $co{'id'};
5878 my $remote_heads = gitweb_check_feature('remote_heads');
5880 my $owner = git_get_project_owner($project);
5882 my $refs = git_get_references();
5883 # These get_*_list functions return one more to allow us to see if
5884 # there are more ...
5885 my @taglist = git_get_tags_list(16);
5886 my @headlist = git_get_heads_list(16);
5887 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
5889 my $check_forks = gitweb_check_feature('forks');
5892 # find forks of a project
5893 @forklist = git_get_projects_list($project);
5894 # filter out forks of forks
5895 @forklist = filter_forks_from_projects_list(\@forklist)
5900 git_print_page_nav('summary','', $head);
5902 print "<div class=\"title\"> </div>\n";
5903 print "<table class=\"projects_list\">\n" .
5904 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
5905 "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
5906 if (defined $cd{'rfc2822'}) {
5907 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
5908 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
5911 # use per project git URL list in $projectroot/$project/cloneurl
5912 # or make project git URL from git base URL and project name
5913 my $url_tag = "URL";
5914 my @url_list = git_get_project_url_list($project);
5915 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
5916 foreach my $git_url (@url_list) {
5917 next unless $git_url;
5918 print format_repo_url($url_tag, $git_url);
5923 my $show_ctags = gitweb_check_feature('ctags');
5925 my $ctags = git_get_project_ctags($project);
5927 # without ability to add tags, don't show if there are none
5928 my $cloud = git_populate_project_tagcloud($ctags);
5929 print "<tr id=\"metadata_ctags\">" .
5930 "<td>content tags</td>" .
5931 "<td>".git_show_project_tagcloud($cloud, 48)."</td>" .
5938 # If XSS prevention is on, we don't include README.html.
5939 # TODO: Allow a readme in some safe format.
5940 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
5941 print "<div class=\"title\">readme</div>\n" .
5942 "<div class=\"readme\">\n";
5943 insert_file("$projectroot/$project/README.html");
5944 print "\n</div>\n"; # class="readme"
5947 # we need to request one more than 16 (0..15) to check if
5949 my @commitlist = $head ? parse_commits($head, 17) : ();
5951 git_print_header_div('shortlog');
5952 git_shortlog_body(\@commitlist, 0, 15, $refs,
5953 $#commitlist <= 15 ? undef :
5954 $cgi->a({-href => href(action=>"shortlog")}, "..."));
5958 git_print_header_div('tags');
5959 git_tags_body(\@taglist, 0, 15,
5960 $#taglist <= 15 ? undef :
5961 $cgi->a({-href => href(action=>"tags")}, "..."));
5965 git_print_header_div('heads');
5966 git_heads_body(\@headlist, $head, 0, 15,
5967 $#headlist <= 15 ? undef :
5968 $cgi->a({-href => href(action=>"heads")}, "..."));
5972 git_print_header_div('remotes');
5973 git_remotes_body(\%remotedata, 15, $head);
5977 git_print_header_div('forks');
5978 git_project_list_body(\@forklist, 'age', 0, 15,
5979 $#forklist <= 15 ? undef :
5980 $cgi->a({-href => href(action=>"forks")}, "..."),
5988 my %tag = parse_tag($hash);
5991 die_error(404, "Unknown tag object");
5994 my $head = git_get_head_hash($project);
5996 git_print_page_nav('','', $head,undef,$head);
5997 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
5998 print "<div class=\"title_text\">\n" .
5999 "<table class=\"object_header\">\n" .
6001 "<td>object</td>\n" .
6002 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6003 $tag{'object'}) . "</td>\n" .
6004 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
6005 $tag{'type'}) . "</td>\n" .
6007 if (defined($tag{'author'})) {
6008 git_print_authorship_rows(\%tag, 'author');
6010 print "</table>\n\n" .
6012 print "<div class=\"page_body\">";
6013 my $comment = $tag{'comment'};
6014 foreach my $line (@$comment) {
6016 print esc_html($line, -nbsp=>1) . "<br/>\n";
6022 sub git_blame_common {
6023 my $format = shift || 'porcelain';
6024 if ($format eq 'porcelain' && $cgi->param('js')) {
6025 $format = 'incremental';
6026 $action = 'blame_incremental'; # for page title etc
6030 gitweb_check_feature('blame')
6031 or die_error(403, "Blame view not allowed");
6034 die_error(400, "No file name given") unless $file_name;
6035 $hash_base ||= git_get_head_hash($project);
6036 die_error(404, "Couldn't find base commit") unless $hash_base;
6037 my %co = parse_commit($hash_base)
6038 or die_error(404, "Commit not found");
6040 if (!defined $hash) {
6041 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
6042 or die_error(404, "Error looking up file");
6044 $ftype = git_get_type($hash);
6045 if ($ftype !~ "blob") {
6046 die_error(400, "Object is not a blob");
6051 if ($format eq 'incremental') {
6052 # get file contents (as base)
6053 open $fd, "-|", git_cmd(), 'cat-file', 'blob', $hash
6054 or die_error(500, "Open git-cat-file failed");
6055 } elsif ($format eq 'data') {
6056 # run git-blame --incremental
6057 open $fd, "-|", git_cmd(), "blame", "--incremental",
6058 $hash_base, "--", $file_name
6059 or die_error(500, "Open git-blame --incremental failed");
6061 # run git-blame --porcelain
6062 open $fd, "-|", git_cmd(), "blame", '-p',
6063 $hash_base, '--', $file_name
6064 or die_error(500, "Open git-blame --porcelain failed");
6067 # incremental blame data returns early
6068 if ($format eq 'data') {
6070 -type=>"text/plain", -charset => "utf-8",
6071 -status=> "200 OK");
6072 local $| = 1; # output autoflush
6075 or print "ERROR $!\n";
6078 if (defined $t0 && gitweb_check_feature('timed')) {
6080 tv_interval($t0, [ gettimeofday() ]).
6081 ' '.$number_of_git_cmds;
6091 $cgi->a({-href => href(action=>"blob", -replay=>1)},
6094 if ($format eq 'incremental') {
6096 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
6097 "blame") . " (non-incremental)";
6100 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
6101 "blame") . " (incremental)";
6105 $cgi->a({-href => href(action=>"history", -replay=>1)},
6108 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
6110 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6111 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6112 git_print_page_path($file_name, $ftype, $hash_base);
6115 if ($format eq 'incremental') {
6116 print "<noscript>\n<div class=\"error\"><center><b>\n".
6117 "This page requires JavaScript to run.\n Use ".
6118 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
6121 "</b></center></div>\n</noscript>\n";
6123 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
6126 print qq!<div class="page_body">\n!;
6127 print qq!<div id="progress_info">... / ...</div>\n!
6128 if ($format eq 'incremental');
6129 print qq!<table id="blame_table" class="blame" width="100%">\n!.
6130 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
6132 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
6136 my @rev_color = qw(light dark);
6137 my $num_colors = scalar(@rev_color);
6138 my $current_color = 0;
6140 if ($format eq 'incremental') {
6141 my $color_class = $rev_color[$current_color];
6146 while (my $line = <$fd>) {
6150 print qq!<tr id="l$linenr" class="$color_class">!.
6151 qq!<td class="sha1"><a href=""> </a></td>!.
6152 qq!<td class="linenr">!.
6153 qq!<a class="linenr" href="">$linenr</a></td>!;
6154 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
6158 } else { # porcelain, i.e. ordinary blame
6159 my %metainfo = (); # saves information about commits
6163 while (my $line = <$fd>) {
6165 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
6166 # no <lines in group> for subsequent lines in group of lines
6167 my ($full_rev, $orig_lineno, $lineno, $group_size) =
6168 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
6169 if (!exists $metainfo{$full_rev}) {
6170 $metainfo{$full_rev} = { 'nprevious' => 0 };
6172 my $meta = $metainfo{$full_rev};
6174 while ($data = <$fd>) {
6176 last if ($data =~ s/^\t//); # contents of line
6177 if ($data =~ /^(\S+)(?: (.*))?$/) {
6178 $meta->{$1} = $2 unless exists $meta->{$1};
6180 if ($data =~ /^previous /) {
6181 $meta->{'nprevious'}++;
6184 my $short_rev = substr($full_rev, 0, 8);
6185 my $author = $meta->{'author'};
6187 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
6188 my $date = $date{'iso-tz'};
6190 $current_color = ($current_color + 1) % $num_colors;
6192 my $tr_class = $rev_color[$current_color];
6193 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
6194 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
6195 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
6196 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
6198 print "<td class=\"sha1\"";
6199 print " title=\"". esc_html($author) . ", $date\"";
6200 print " rowspan=\"$group_size\"" if ($group_size > 1);
6202 print $cgi->a({-href => href(action=>"commit",
6204 file_name=>$file_name)},
6205 esc_html($short_rev));
6206 if ($group_size >= 2) {
6207 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
6208 if (@author_initials) {
6210 esc_html(join('', @author_initials));
6216 # 'previous' <sha1 of parent commit> <filename at commit>
6217 if (exists $meta->{'previous'} &&
6218 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
6219 $meta->{'parent'} = $1;
6220 $meta->{'file_parent'} = unquote($2);
6223 exists($meta->{'parent'}) ?
6224 $meta->{'parent'} : $full_rev;
6225 my $linenr_filename =
6226 exists($meta->{'file_parent'}) ?
6227 $meta->{'file_parent'} : unquote($meta->{'filename'});
6228 my $blamed = href(action => 'blame',
6229 file_name => $linenr_filename,
6230 hash_base => $linenr_commit);
6231 print "<td class=\"linenr\">";
6232 print $cgi->a({ -href => "$blamed#l$orig_lineno",
6233 -class => "linenr" },
6236 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
6244 "</table>\n"; # class="blame"
6245 print "</div>\n"; # class="blame_body"
6247 or print "Reading blob failed\n";
6256 sub git_blame_incremental {
6257 git_blame_common('incremental');
6260 sub git_blame_data {
6261 git_blame_common('data');
6265 my $head = git_get_head_hash($project);
6267 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
6268 git_print_header_div('summary', $project);
6270 my @tagslist = git_get_tags_list();
6272 git_tags_body(\@tagslist);
6278 my $head = git_get_head_hash($project);
6280 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
6281 git_print_header_div('summary', $project);
6283 my @headslist = git_get_heads_list();
6285 git_heads_body(\@headslist, $head);
6290 # used both for single remote view and for list of all the remotes
6292 gitweb_check_feature('remote_heads')
6293 or die_error(403, "Remote heads view is disabled");
6295 my $head = git_get_head_hash($project);
6296 my $remote = $input_params{'hash'};
6298 my $remotedata = git_get_remotes_list($remote);
6299 die_error(500, "Unable to get remote information") unless defined $remotedata;
6301 unless (%$remotedata) {
6302 die_error(404, defined $remote ?
6303 "Remote $remote not found" :
6304 "No remotes found");
6307 git_header_html(undef, undef, -action_extra => $remote);
6308 git_print_page_nav('', '', $head, undef, $head,
6309 format_ref_views($remote ? '' : 'remotes'));
6311 fill_remote_heads($remotedata);
6312 if (defined $remote) {
6313 git_print_header_div('remotes', "$remote remote for $project");
6314 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
6316 git_print_header_div('summary', "$project remotes");
6317 git_remotes_body($remotedata, undef, $head);
6323 sub git_blob_plain {
6327 if (!defined $hash) {
6328 if (defined $file_name) {
6329 my $base = $hash_base || git_get_head_hash($project);
6330 $hash = git_get_hash_by_path($base, $file_name, "blob")
6331 or die_error(404, "Cannot find file");
6333 die_error(400, "No file name defined");
6335 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6336 # blobs defined by non-textual hash id's can be cached
6340 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
6341 or die_error(500, "Open git-cat-file blob '$hash' failed");
6343 # content-type (can include charset)
6344 $type = blob_contenttype($fd, $file_name, $type);
6346 # "save as" filename, even when no $file_name is given
6347 my $save_as = "$hash";
6348 if (defined $file_name) {
6349 $save_as = $file_name;
6350 } elsif ($type =~ m/^text\//) {
6354 # With XSS prevention on, blobs of all types except a few known safe
6355 # ones are served with "Content-Disposition: attachment" to make sure
6356 # they don't run in our security domain. For certain image types,
6357 # blob view writes an <img> tag referring to blob_plain view, and we
6358 # want to be sure not to break that by serving the image as an
6359 # attachment (though Firefox 3 doesn't seem to care).
6360 my $sandbox = $prevent_xss &&
6361 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
6363 # serve text/* as text/plain
6365 ($type =~ m!^text/[a-z]+\b(.*)$! ||
6366 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
6368 $rest = defined $rest ? $rest : '';
6369 $type = "text/plain$rest";
6374 -expires => $expires,
6375 -content_disposition =>
6376 ($sandbox ? 'attachment' : 'inline')
6377 . '; filename="' . $save_as . '"');
6379 binmode STDOUT, ':raw';
6381 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
6388 if (!defined $hash) {
6389 if (defined $file_name) {
6390 my $base = $hash_base || git_get_head_hash($project);
6391 $hash = git_get_hash_by_path($base, $file_name, "blob")
6392 or die_error(404, "Cannot find file");
6394 die_error(400, "No file name defined");
6396 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6397 # blobs defined by non-textual hash id's can be cached
6401 my $have_blame = gitweb_check_feature('blame');
6402 open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
6403 or die_error(500, "Couldn't cat $file_name, $hash");
6404 my $mimetype = blob_mimetype($fd, $file_name);
6405 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
6406 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
6408 return git_blob_plain($mimetype);
6410 # we can have blame only for text/* mimetype
6411 $have_blame &&= ($mimetype =~ m!^text/!);
6413 my $highlight = gitweb_check_feature('highlight');
6414 my $syntax = guess_file_syntax($highlight, $mimetype, $file_name);
6415 $fd = run_highlighter($fd, $highlight, $syntax)
6418 git_header_html(undef, $expires);
6419 my $formats_nav = '';
6420 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6421 if (defined $file_name) {
6424 $cgi->a({-href => href(action=>"blame", -replay=>1)},
6429 $cgi->a({-href => href(action=>"history", -replay=>1)},
6432 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
6435 $cgi->a({-href => href(action=>"blob",
6436 hash_base=>"HEAD", file_name=>$file_name)},
6440 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
6443 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6444 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6446 print "<div class=\"page_nav\">\n" .
6447 "<br/><br/></div>\n" .
6448 "<div class=\"title\">".esc_html($hash)."</div>\n";
6450 git_print_page_path($file_name, "blob", $hash_base);
6451 print "<div class=\"page_body\">\n";
6452 if ($mimetype =~ m!^image/!) {
6453 print qq!<img type="!.esc_attr($mimetype).qq!"!;
6455 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
6458 href(action=>"blob_plain", hash=>$hash,
6459 hash_base=>$hash_base, file_name=>$file_name) .
6463 while (my $line = <$fd>) {
6466 $line = untabify($line);
6467 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
6468 $nr, esc_attr(href(-replay => 1)), $nr, $nr, $syntax ? $line : esc_html($line, -nbsp=>1);
6472 or print "Reading blob failed.\n";
6478 if (!defined $hash_base) {
6479 $hash_base = "HEAD";
6481 if (!defined $hash) {
6482 if (defined $file_name) {
6483 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
6488 die_error(404, "No such tree") unless defined($hash);
6490 my $show_sizes = gitweb_check_feature('show-sizes');
6491 my $have_blame = gitweb_check_feature('blame');
6496 open my $fd, "-|", git_cmd(), "ls-tree", '-z',
6497 ($show_sizes ? '-l' : ()), @extra_options, $hash
6498 or die_error(500, "Open git-ls-tree failed");
6499 @entries = map { chomp; $_ } <$fd>;
6501 or die_error(404, "Reading tree failed");
6504 my $refs = git_get_references();
6505 my $ref = format_ref_marker($refs, $hash_base);
6508 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6510 if (defined $file_name) {
6512 $cgi->a({-href => href(action=>"history", -replay=>1)},
6514 $cgi->a({-href => href(action=>"tree",
6515 hash_base=>"HEAD", file_name=>$file_name)},
6518 my $snapshot_links = format_snapshot_links($hash);
6519 if (defined $snapshot_links) {
6520 # FIXME: Should be available when we have no hash base as well.
6521 push @views_nav, $snapshot_links;
6523 git_print_page_nav('tree','', $hash_base, undef, undef,
6524 join(' | ', @views_nav));
6525 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
6528 print "<div class=\"page_nav\">\n";
6529 print "<br/><br/></div>\n";
6530 print "<div class=\"title\">".esc_html($hash)."</div>\n";
6532 if (defined $file_name) {
6533 $basedir = $file_name;
6534 if ($basedir ne '' && substr($basedir, -1) ne '/') {
6537 git_print_page_path($file_name, 'tree', $hash_base);
6539 print "<div class=\"page_body\">\n";
6540 print "<table class=\"tree\">\n";
6542 # '..' (top directory) link if possible
6543 if (defined $hash_base &&
6544 defined $file_name && $file_name =~ m![^/]+$!) {
6546 print "<tr class=\"dark\">\n";
6548 print "<tr class=\"light\">\n";
6552 my $up = $file_name;
6553 $up =~ s!/?[^/]+$!!;
6554 undef $up unless $up;
6555 # based on git_print_tree_entry
6556 print '<td class="mode">' . mode_str('040000') . "</td>\n";
6557 print '<td class="size"> </td>'."\n" if $show_sizes;
6558 print '<td class="list">';
6559 print $cgi->a({-href => href(action=>"tree",
6560 hash_base=>$hash_base,
6564 print "<td class=\"link\"></td>\n";
6568 foreach my $line (@entries) {
6569 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
6572 print "<tr class=\"dark\">\n";
6574 print "<tr class=\"light\">\n";
6578 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
6582 print "</table>\n" .
6588 my ($project, $hash) = @_;
6590 # path/to/project.git -> project
6591 # path/to/project/.git -> project
6592 my $name = to_utf8($project);
6593 $name =~ s,([^/])/*\.git$,$1,;
6594 $name = basename($name);
6596 $name =~ s/[[:cntrl:]]/?/g;
6599 if ($hash =~ /^[0-9a-fA-F]+$/) {
6600 # shorten SHA-1 hash
6601 my $full_hash = git_get_full_hash($project, $hash);
6602 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
6603 $ver = git_get_short_hash($project, $hash);
6605 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
6606 # tags don't need shortened SHA-1 hash
6609 # branches and other need shortened SHA-1 hash
6610 if ($hash =~ m!^refs/(?:heads|remotes)/(.*)$!) {
6613 $ver .= '-' . git_get_short_hash($project, $hash);
6615 # in case of hierarchical branch names
6618 # name = project-version_string
6619 $name = "$name-$ver";
6621 return wantarray ? ($name, $name) : $name;
6625 my $format = $input_params{'snapshot_format'};
6626 if (!@snapshot_fmts) {
6627 die_error(403, "Snapshots not allowed");
6629 # default to first supported snapshot format
6630 $format ||= $snapshot_fmts[0];
6631 if ($format !~ m/^[a-z0-9]+$/) {
6632 die_error(400, "Invalid snapshot format parameter");
6633 } elsif (!exists($known_snapshot_formats{$format})) {
6634 die_error(400, "Unknown snapshot format");
6635 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
6636 die_error(403, "Snapshot format not allowed");
6637 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
6638 die_error(403, "Unsupported snapshot format");
6641 my $type = git_get_type("$hash^{}");
6643 die_error(404, 'Object does not exist');
6644 } elsif ($type eq 'blob') {
6645 die_error(400, 'Object is not a tree-ish');
6648 my ($name, $prefix) = snapshot_name($project, $hash);
6649 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
6650 my $cmd = quote_command(
6651 git_cmd(), 'archive',
6652 "--format=$known_snapshot_formats{$format}{'format'}",
6653 "--prefix=$prefix/", $hash);
6654 if (exists $known_snapshot_formats{$format}{'compressor'}) {
6655 $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
6658 $filename =~ s/(["\\])/\\$1/g;
6660 -type => $known_snapshot_formats{$format}{'type'},
6661 -content_disposition => 'inline; filename="' . $filename . '"',
6662 -status => '200 OK');
6664 open my $fd, "-|", $cmd
6665 or die_error(500, "Execute git-archive failed");
6666 binmode STDOUT, ':raw';
6668 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
6672 sub git_log_generic {
6673 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
6675 my $head = git_get_head_hash($project);
6676 if (!defined $base) {
6679 if (!defined $page) {
6682 my $refs = git_get_references();
6684 my $commit_hash = $base;
6685 if (defined $parent) {
6686 $commit_hash = "$parent..$base";
6689 parse_commits($commit_hash, 101, (100 * $page),
6690 defined $file_name ? ($file_name, "--full-history") : ());
6693 if (!defined $file_hash && defined $file_name) {
6694 # some commits could have deleted file in question,
6695 # and not have it in tree, but one of them has to have it
6696 for (my $i = 0; $i < @commitlist; $i++) {
6697 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
6698 last if defined $file_hash;
6701 if (defined $file_hash) {
6702 $ftype = git_get_type($file_hash);
6704 if (defined $file_name && !defined $ftype) {
6705 die_error(500, "Unknown type of object");
6708 if (defined $file_name) {
6709 %co = parse_commit($base)
6710 or die_error(404, "Unknown commit object");
6714 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
6716 if ($#commitlist >= 100) {
6718 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6719 -accesskey => "n", -title => "Alt-n"}, "next");
6721 my $patch_max = gitweb_get_feature('patches');
6722 if ($patch_max && !defined $file_name) {
6723 if ($patch_max < 0 || @commitlist <= $patch_max) {
6724 $paging_nav .= " ⋅ " .
6725 $cgi->a({-href => href(action=>"patches", -replay=>1)},
6731 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
6732 if (defined $file_name) {
6733 git_print_header_div('commit', esc_html($co{'title'}), $base);
6735 git_print_header_div('summary', $project)
6737 git_print_page_path($file_name, $ftype, $hash_base)
6738 if (defined $file_name);
6740 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
6741 $file_name, $file_hash, $ftype);
6747 git_log_generic('log', \&git_log_body,
6748 $hash, $hash_parent);
6752 $hash ||= $hash_base || "HEAD";
6753 my %co = parse_commit($hash)
6754 or die_error(404, "Unknown commit object");
6756 my $parent = $co{'parent'};
6757 my $parents = $co{'parents'}; # listref
6759 # we need to prepare $formats_nav before any parameter munging
6761 if (!defined $parent) {
6763 $formats_nav .= '(initial)';
6764 } elsif (@$parents == 1) {
6765 # single parent commit
6768 $cgi->a({-href => href(action=>"commit",
6770 esc_html(substr($parent, 0, 7))) .
6777 $cgi->a({-href => href(action=>"commit",
6779 esc_html(substr($_, 0, 7)));
6783 if (gitweb_check_feature('patches') && @$parents <= 1) {
6784 $formats_nav .= " | " .
6785 $cgi->a({-href => href(action=>"patch", -replay=>1)},
6789 if (!defined $parent) {
6793 open my $fd, "-|", git_cmd(), "diff-tree", '-r', "--no-commit-id",
6795 (@$parents <= 1 ? $parent : '-c'),
6797 or die_error(500, "Open git-diff-tree failed");
6798 @difftree = map { chomp; $_ } <$fd>;
6799 close $fd or die_error(404, "Reading git-diff-tree failed");
6801 # non-textual hash id's can be cached
6803 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
6806 my $refs = git_get_references();
6807 my $ref = format_ref_marker($refs, $co{'id'});
6809 git_header_html(undef, $expires);
6810 git_print_page_nav('commit', '',
6811 $hash, $co{'tree'}, $hash,
6814 if (defined $co{'parent'}) {
6815 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
6817 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
6819 print "<div class=\"title_text\">\n" .
6820 "<table class=\"object_header\">\n";
6821 git_print_authorship_rows(\%co);
6822 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
6825 "<td class=\"sha1\">" .
6826 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
6827 class => "list"}, $co{'tree'}) .
6829 "<td class=\"link\">" .
6830 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
6832 my $snapshot_links = format_snapshot_links($hash);
6833 if (defined $snapshot_links) {
6834 print " | " . $snapshot_links;
6839 foreach my $par (@$parents) {
6842 "<td class=\"sha1\">" .
6843 $cgi->a({-href => href(action=>"commit", hash=>$par),
6844 class => "list"}, $par) .
6846 "<td class=\"link\">" .
6847 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
6849 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
6856 print "<div class=\"page_body\">\n";
6857 git_print_log($co{'comment'});
6860 git_difftree_body(\@difftree, $hash, @$parents);
6866 # object is defined by:
6867 # - hash or hash_base alone
6868 # - hash_base and file_name
6871 # - hash or hash_base alone
6872 if ($hash || ($hash_base && !defined $file_name)) {
6873 my $object_id = $hash || $hash_base;
6875 open my $fd, "-|", quote_command(
6876 git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
6877 or die_error(404, "Object does not exist");
6881 or die_error(404, "Object does not exist");
6883 # - hash_base and file_name
6884 } elsif ($hash_base && defined $file_name) {
6885 $file_name =~ s,/+$,,;
6887 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
6888 or die_error(404, "Base object does not exist");
6890 # here errors should not hapen
6891 open my $fd, "-|", git_cmd(), "ls-tree", $hash_base, "--", $file_name
6892 or die_error(500, "Open git-ls-tree failed");
6896 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
6897 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
6898 die_error(404, "File or directory for given base does not exist");
6903 die_error(400, "Not enough information to find object");
6906 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
6907 hash=>$hash, hash_base=>$hash_base,
6908 file_name=>$file_name),
6909 -status => '302 Found');
6913 my $format = shift || 'html';
6920 # preparing $fd and %diffinfo for git_patchset_body
6922 if (defined $hash_base && defined $hash_parent_base) {
6923 if (defined $file_name) {
6925 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6926 $hash_parent_base, $hash_base,
6927 "--", (defined $file_parent ? $file_parent : ()), $file_name
6928 or die_error(500, "Open git-diff-tree failed");
6929 @difftree = map { chomp; $_ } <$fd>;
6931 or die_error(404, "Reading git-diff-tree failed");
6933 or die_error(404, "Blob diff not found");
6935 } elsif (defined $hash &&
6936 $hash =~ /[0-9a-fA-F]{40}/) {
6937 # try to find filename from $hash
6939 # read filtered raw output
6940 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6941 $hash_parent_base, $hash_base, "--"
6942 or die_error(500, "Open git-diff-tree failed");
6944 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
6946 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
6947 map { chomp; $_ } <$fd>;
6949 or die_error(404, "Reading git-diff-tree failed");
6951 or die_error(404, "Blob diff not found");
6954 die_error(400, "Missing one of the blob diff parameters");
6957 if (@difftree > 1) {
6958 die_error(400, "Ambiguous blob diff specification");
6961 %diffinfo = parse_difftree_raw_line($difftree[0]);
6962 $file_parent ||= $diffinfo{'from_file'} || $file_name;
6963 $file_name ||= $diffinfo{'to_file'};
6965 $hash_parent ||= $diffinfo{'from_id'};
6966 $hash ||= $diffinfo{'to_id'};
6968 # non-textual hash id's can be cached
6969 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
6970 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
6975 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
6976 '-p', ($format eq 'html' ? "--full-index" : ()),
6977 $hash_parent_base, $hash_base,
6978 "--", (defined $file_parent ? $file_parent : ()), $file_name
6979 or die_error(500, "Open git-diff-tree failed");
6982 # old/legacy style URI -- not generated anymore since 1.4.3.
6984 die_error('404 Not Found', "Missing one of the blob diff parameters")
6988 if ($format eq 'html') {
6990 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
6992 git_header_html(undef, $expires);
6993 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
6994 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
6995 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
6997 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
6998 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
7000 if (defined $file_name) {
7001 git_print_page_path($file_name, "blob", $hash_base);
7003 print "<div class=\"page_path\"></div>\n";
7006 } elsif ($format eq 'plain') {
7008 -type => 'text/plain',
7009 -charset => 'utf-8',
7010 -expires => $expires,
7011 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
7013 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7016 die_error(400, "Unknown blobdiff format");
7020 if ($format eq 'html') {
7021 print "<div class=\"page_body\">\n";
7023 git_patchset_body($fd, [ \%diffinfo ], $hash_base, $hash_parent_base);
7026 print "</div>\n"; # class="page_body"
7030 while (my $line = <$fd>) {
7031 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
7032 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
7036 last if $line =~ m!^\+\+\+!;
7044 sub git_blobdiff_plain {
7045 git_blobdiff('plain');
7048 sub git_commitdiff {
7050 my $format = $params{-format} || 'html';
7052 my ($patch_max) = gitweb_get_feature('patches');
7053 if ($format eq 'patch') {
7054 die_error(403, "Patch view not allowed") unless $patch_max;
7057 $hash ||= $hash_base || "HEAD";
7058 my %co = parse_commit($hash)
7059 or die_error(404, "Unknown commit object");
7061 # choose format for commitdiff for merge
7062 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
7063 $hash_parent = '--cc';
7065 # we need to prepare $formats_nav before almost any parameter munging
7067 if ($format eq 'html') {
7069 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
7071 if ($patch_max && @{$co{'parents'}} <= 1) {
7072 $formats_nav .= " | " .
7073 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7077 if (defined $hash_parent &&
7078 $hash_parent ne '-c' && $hash_parent ne '--cc') {
7079 # commitdiff with two commits given
7080 my $hash_parent_short = $hash_parent;
7081 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
7082 $hash_parent_short = substr($hash_parent, 0, 7);
7086 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
7087 if ($co{'parents'}[$i] eq $hash_parent) {
7088 $formats_nav .= ' parent ' . ($i+1);
7092 $formats_nav .= ': ' .
7093 $cgi->a({-href => href(action=>"commitdiff",
7094 hash=>$hash_parent)},
7095 esc_html($hash_parent_short)) .
7097 } elsif (!$co{'parent'}) {
7099 $formats_nav .= ' (initial)';
7100 } elsif (scalar @{$co{'parents'}} == 1) {
7101 # single parent commit
7104 $cgi->a({-href => href(action=>"commitdiff",
7105 hash=>$co{'parent'})},
7106 esc_html(substr($co{'parent'}, 0, 7))) .
7110 if ($hash_parent eq '--cc') {
7111 $formats_nav .= ' | ' .
7112 $cgi->a({-href => href(action=>"commitdiff",
7113 hash=>$hash, hash_parent=>'-c')},
7115 } else { # $hash_parent eq '-c'
7116 $formats_nav .= ' | ' .
7117 $cgi->a({-href => href(action=>"commitdiff",
7118 hash=>$hash, hash_parent=>'--cc')},
7124 $cgi->a({-href => href(action=>"commitdiff",
7126 esc_html(substr($_, 0, 7)));
7127 } @{$co{'parents'}} ) .
7132 my $hash_parent_param = $hash_parent;
7133 if (!defined $hash_parent_param) {
7134 # --cc for multiple parents, --root for parentless
7135 $hash_parent_param =
7136 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
7142 if ($format eq 'html') {
7143 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7144 "--no-commit-id", "--patch-with-raw", "--full-index",
7145 $hash_parent_param, $hash, "--"
7146 or die_error(500, "Open git-diff-tree failed");
7148 while (my $line = <$fd>) {
7150 # empty line ends raw part of diff-tree output
7152 push @difftree, scalar parse_difftree_raw_line($line);
7155 } elsif ($format eq 'plain') {
7156 open $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7157 '-p', $hash_parent_param, $hash, "--"
7158 or die_error(500, "Open git-diff-tree failed");
7159 } elsif ($format eq 'patch') {
7160 # For commit ranges, we limit the output to the number of
7161 # patches specified in the 'patches' feature.
7162 # For single commits, we limit the output to a single patch,
7163 # diverging from the git-format-patch default.
7164 my @commit_spec = ();
7166 if ($patch_max > 0) {
7167 push @commit_spec, "-$patch_max";
7169 push @commit_spec, '-n', "$hash_parent..$hash";
7171 if ($params{-single}) {
7172 push @commit_spec, '-1';
7174 if ($patch_max > 0) {
7175 push @commit_spec, "-$patch_max";
7177 push @commit_spec, "-n";
7179 push @commit_spec, '--root', $hash;
7181 open $fd, "-|", git_cmd(), "format-patch", @diff_opts,
7182 '--encoding=utf8', '--stdout', @commit_spec
7183 or die_error(500, "Open git-format-patch failed");
7185 die_error(400, "Unknown commitdiff format");
7188 # non-textual hash id's can be cached
7190 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7194 # write commit message
7195 if ($format eq 'html') {
7196 my $refs = git_get_references();
7197 my $ref = format_ref_marker($refs, $co{'id'});
7199 git_header_html(undef, $expires);
7200 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
7201 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
7202 print "<div class=\"title_text\">\n" .
7203 "<table class=\"object_header\">\n";
7204 git_print_authorship_rows(\%co);
7207 print "<div class=\"page_body\">\n";
7208 if (@{$co{'comment'}} > 1) {
7209 print "<div class=\"log\">\n";
7210 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
7211 print "</div>\n"; # class="log"
7214 } elsif ($format eq 'plain') {
7215 my $refs = git_get_references("tags");
7216 my $tagname = git_get_rev_name_tags($hash);
7217 my $filename = basename($project) . "-$hash.patch";
7220 -type => 'text/plain',
7221 -charset => 'utf-8',
7222 -expires => $expires,
7223 -content_disposition => 'inline; filename="' . "$filename" . '"');
7224 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
7225 print "From: " . to_utf8($co{'author'}) . "\n";
7226 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
7227 print "Subject: " . to_utf8($co{'title'}) . "\n";
7229 print "X-Git-Tag: $tagname\n" if $tagname;
7230 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
7232 foreach my $line (@{$co{'comment'}}) {
7233 print to_utf8($line) . "\n";
7236 } elsif ($format eq 'patch') {
7237 my $filename = basename($project) . "-$hash.patch";
7240 -type => 'text/plain',
7241 -charset => 'utf-8',
7242 -expires => $expires,
7243 -content_disposition => 'inline; filename="' . "$filename" . '"');
7247 if ($format eq 'html') {
7248 my $use_parents = !defined $hash_parent ||
7249 $hash_parent eq '-c' || $hash_parent eq '--cc';
7250 git_difftree_body(\@difftree, $hash,
7251 $use_parents ? @{$co{'parents'}} : $hash_parent);
7254 git_patchset_body($fd, \@difftree, $hash,
7255 $use_parents ? @{$co{'parents'}} : $hash_parent);
7257 print "</div>\n"; # class="page_body"
7260 } elsif ($format eq 'plain') {
7264 or print "Reading git-diff-tree failed\n";
7265 } elsif ($format eq 'patch') {
7269 or print "Reading git-format-patch failed\n";
7273 sub git_commitdiff_plain {
7274 git_commitdiff(-format => 'plain');
7277 # format-patch-style patches
7279 git_commitdiff(-format => 'patch', -single => 1);
7283 git_commitdiff(-format => 'patch');
7287 git_log_generic('history', \&git_history_body,
7288 $hash_base, $hash_parent_base,
7293 $searchtype ||= 'commit';
7295 # check if appropriate features are enabled
7296 gitweb_check_feature('search')
7297 or die_error(403, "Search is disabled");
7298 if ($searchtype eq 'pickaxe') {
7299 # pickaxe may take all resources of your box and run for several minutes
7300 # with every query - so decide by yourself how public you make this feature
7301 gitweb_check_feature('pickaxe')
7302 or die_error(403, "Pickaxe search is disabled");
7304 if ($searchtype eq 'grep') {
7305 # grep search might be potentially CPU-intensive, too
7306 gitweb_check_feature('grep')
7307 or die_error(403, "Grep search is disabled");
7310 if (!defined $searchtext) {
7311 die_error(400, "Text field is empty");
7313 if (!defined $hash) {
7314 $hash = git_get_head_hash($project);
7316 my %co = parse_commit($hash);
7318 die_error(404, "Unknown commit object");
7320 if (!defined $page) {
7324 if ($searchtype eq 'commit' ||
7325 $searchtype eq 'author' ||
7326 $searchtype eq 'committer') {
7327 git_search_message(%co);
7328 } elsif ($searchtype eq 'pickaxe') {
7329 git_search_changes(%co);
7330 } elsif ($searchtype eq 'grep') {
7331 git_search_files(%co);
7333 die_error(400, "Unknown search type");
7337 sub git_search_help {
7339 git_print_page_nav('','', $hash,$hash,$hash);
7341 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
7342 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
7343 the pattern entered is recognized as the POSIX extended
7344 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
7347 <dt><b>commit</b></dt>
7348 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
7350 my $have_grep = gitweb_check_feature('grep');
7353 <dt><b>grep</b></dt>
7354 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
7355 a different one) are searched for the given pattern. On large trees, this search can take
7356 a while and put some strain on the server, so please use it with some consideration. Note that
7357 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
7358 case-sensitive.</dd>
7362 <dt><b>author</b></dt>
7363 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
7364 <dt><b>committer</b></dt>
7365 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
7367 my $have_pickaxe = gitweb_check_feature('pickaxe');
7368 if ($have_pickaxe) {
7370 <dt><b>pickaxe</b></dt>
7371 <dd>All commits that caused the string to appear or disappear from any file (changes that
7372 added, removed or "modified" the string) will be listed. This search can take a while and
7373 takes a lot of strain on the server, so please use it wisely. Note that since you may be
7374 interested even in changes just changing the case as well, this search is case sensitive.</dd>
7382 git_log_generic('shortlog', \&git_shortlog_body,
7383 $hash, $hash_parent);
7386 ## ......................................................................
7387 ## feeds (RSS, Atom; OPML)
7390 my $format = shift || 'atom';
7391 my $have_blame = gitweb_check_feature('blame');
7393 # Atom: http://www.atomenabled.org/developers/syndication/
7394 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
7395 if ($format ne 'rss' && $format ne 'atom') {
7396 die_error(400, "Unknown web feed format");
7399 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
7400 my $head = $hash || 'HEAD';
7401 my @commitlist = parse_commits($head, 150, 0, $file_name);
7405 my $content_type = "application/$format+xml";
7406 if (defined $cgi->http('HTTP_ACCEPT') &&
7407 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
7408 # browser (feed reader) prefers text/xml
7409 $content_type = 'text/xml';
7411 if (defined($commitlist[0])) {
7412 %latest_commit = %{$commitlist[0]};
7413 my $latest_epoch = $latest_commit{'committer_epoch'};
7414 %latest_date = parse_date($latest_epoch, $latest_commit{'comitter_tz'});
7415 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7416 if (defined $if_modified) {
7418 if (eval { require HTTP::Date; 1; }) {
7419 $since = HTTP::Date::str2time($if_modified);
7420 } elsif (eval { require Time::ParseDate; 1; }) {
7421 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7423 if (defined $since && $latest_epoch <= $since) {
7425 -type => $content_type,
7426 -charset => 'utf-8',
7427 -last_modified => $latest_date{'rfc2822'},
7428 -status => '304 Not Modified');
7433 -type => $content_type,
7434 -charset => 'utf-8',
7435 -last_modified => $latest_date{'rfc2822'});
7438 -type => $content_type,
7439 -charset => 'utf-8');
7442 # Optimization: skip generating the body if client asks only
7443 # for Last-Modified date.
7444 return if ($cgi->request_method() eq 'HEAD');
7447 my $title = "$site_name - $project/$action";
7448 my $feed_type = 'log';
7449 if (defined $hash) {
7450 $title .= " - '$hash'";
7451 $feed_type = 'branch log';
7452 if (defined $file_name) {
7453 $title .= " :: $file_name";
7454 $feed_type = 'history';
7456 } elsif (defined $file_name) {
7457 $title .= " - $file_name";
7458 $feed_type = 'history';
7460 $title .= " $feed_type";
7461 my $descr = git_get_project_description($project);
7462 if (defined $descr) {
7463 $descr = esc_html($descr);
7465 $descr = "$project " .
7466 ($format eq 'rss' ? 'RSS' : 'Atom') .
7469 my $owner = git_get_project_owner($project);
7470 $owner = esc_html($owner);
7474 if (defined $file_name) {
7475 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
7476 } elsif (defined $hash) {
7477 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
7479 $alt_url = href(-full=>1, action=>"summary");
7481 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
7482 if ($format eq 'rss') {
7484 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
7487 print "<title>$title</title>\n" .
7488 "<link>$alt_url</link>\n" .
7489 "<description>$descr</description>\n" .
7490 "<language>en</language>\n" .
7491 # project owner is responsible for 'editorial' content
7492 "<managingEditor>$owner</managingEditor>\n";
7493 if (defined $logo || defined $favicon) {
7494 # prefer the logo to the favicon, since RSS
7495 # doesn't allow both
7496 my $img = esc_url($logo || $favicon);
7498 "<url>$img</url>\n" .
7499 "<title>$title</title>\n" .
7500 "<link>$alt_url</link>\n" .
7504 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
7505 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
7507 print "<generator>gitweb v.$version/$git_version</generator>\n";
7508 } elsif ($format eq 'atom') {
7510 <feed xmlns="http://www.w3.org/2005/Atom">
7512 print "<title>$title</title>\n" .
7513 "<subtitle>$descr</subtitle>\n" .
7514 '<link rel="alternate" type="text/html" href="' .
7515 $alt_url . '" />' . "\n" .
7516 '<link rel="self" type="' . $content_type . '" href="' .
7517 $cgi->self_url() . '" />' . "\n" .
7518 "<id>" . href(-full=>1) . "</id>\n" .
7519 # use project owner for feed author
7520 "<author><name>$owner</name></author>\n";
7521 if (defined $favicon) {
7522 print "<icon>" . esc_url($favicon) . "</icon>\n";
7524 if (defined $logo) {
7525 # not twice as wide as tall: 72 x 27 pixels
7526 print "<logo>" . esc_url($logo) . "</logo>\n";
7528 if (! %latest_date) {
7529 # dummy date to keep the feed valid until commits trickle in:
7530 print "<updated>1970-01-01T00:00:00Z</updated>\n";
7532 print "<updated>$latest_date{'iso-8601'}</updated>\n";
7534 print "<generator version='$version/$git_version'>gitweb</generator>\n";
7538 for (my $i = 0; $i <= $#commitlist; $i++) {
7539 my %co = %{$commitlist[$i]};
7540 my $commit = $co{'id'};
7541 # we read 150, we always show 30 and the ones more recent than 48 hours
7542 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
7545 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
7547 # get list of changed files
7548 open my $fd, "-|", git_cmd(), "diff-tree", '-r', @diff_opts,
7549 $co{'parent'} || "--root",
7550 $co{'id'}, "--", (defined $file_name ? $file_name : ())
7552 my @difftree = map { chomp; $_ } <$fd>;
7556 # print element (entry, item)
7557 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
7558 if ($format eq 'rss') {
7560 "<title>" . esc_html($co{'title'}) . "</title>\n" .
7561 "<author>" . esc_html($co{'author'}) . "</author>\n" .
7562 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
7563 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
7564 "<link>$co_url</link>\n" .
7565 "<description>" . esc_html($co{'title'}) . "</description>\n" .
7566 "<content:encoded>" .
7568 } elsif ($format eq 'atom') {
7570 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
7571 "<updated>$cd{'iso-8601'}</updated>\n" .
7573 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
7574 if ($co{'author_email'}) {
7575 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
7577 print "</author>\n" .
7578 # use committer for contributor
7580 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
7581 if ($co{'committer_email'}) {
7582 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
7584 print "</contributor>\n" .
7585 "<published>$cd{'iso-8601'}</published>\n" .
7586 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
7587 "<id>$co_url</id>\n" .
7588 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
7589 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
7591 my $comment = $co{'comment'};
7593 foreach my $line (@$comment) {
7594 $line = esc_html($line);
7597 print "</pre><ul>\n";
7598 foreach my $difftree_line (@difftree) {
7599 my %difftree = parse_difftree_raw_line($difftree_line);
7600 next if !$difftree{'from_id'};
7602 my $file = $difftree{'file'} || $difftree{'to_file'};
7606 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
7607 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
7608 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
7609 file_name=>$file, file_parent=>$difftree{'from_file'}),
7610 -title => "diff"}, 'D');
7612 print $cgi->a({-href => href(-full=>1, action=>"blame",
7613 file_name=>$file, hash_base=>$commit),
7614 -title => "blame"}, 'B');
7616 # if this is not a feed of a file history
7617 if (!defined $file_name || $file_name ne $file) {
7618 print $cgi->a({-href => href(-full=>1, action=>"history",
7619 file_name=>$file, hash=>$commit),
7620 -title => "history"}, 'H');
7622 $file = esc_path($file);
7626 if ($format eq 'rss') {
7627 print "</ul>]]>\n" .
7628 "</content:encoded>\n" .
7630 } elsif ($format eq 'atom') {
7631 print "</ul>\n</div>\n" .
7638 if ($format eq 'rss') {
7639 print "</channel>\n</rss>\n";
7640 } elsif ($format eq 'atom') {
7654 my @list = git_get_projects_list();
7656 die_error(404, "No projects found");
7660 -type => 'text/xml',
7661 -charset => 'utf-8',
7662 -content_disposition => 'inline; filename="opml.xml"');
7665 <?xml version="1.0" encoding="utf-8"?>
7666 <opml version="1.0">
7668 <title>$site_name OPML Export</title>
7671 <outline text="git RSS feeds">
7674 foreach my $pr (@list) {
7676 my $head = git_get_head_hash($proj{'path'});
7677 if (!defined $head) {
7680 $git_dir = "$projectroot/$proj{'path'}";
7681 my %co = parse_commit($head);
7686 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
7687 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
7688 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
7689 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";