Merge commit 'refs/top-bases/t/misc/blob_plain-charset' into t/misc/blob_plain-charset
[git/gitweb.git] / gitweb / gitweb.perl
blob38ebd6d4d2527fc0f443fa6bfb48054ea18ae851
1 #!/usr/bin/perl
3 # gitweb - simple web interface to track changes in git repositories
5 # (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
6 # (C) 2005, Christian Gierke
8 # This program is licensed under the GPLv2
10 use 5.008;
11 use strict;
12 use warnings;
13 use CGI qw(:standard :escapeHTML -nosticky);
14 use CGI::Util qw(unescape);
15 use CGI::Carp qw(fatalsToBrowser set_message);
16 use Encode;
17 use Fcntl ':mode';
18 use File::Find qw();
19 use File::Basename qw(basename);
20 use File::Spec;
21 use Time::HiRes qw(gettimeofday tv_interval);
22 binmode STDOUT, ':utf8';
24 if (!defined($CGI::VERSION) || $CGI::VERSION < 4.08) {
25 eval 'sub CGI::multi_param { CGI::param(@_) }'
28 our $t0 = [ gettimeofday() ];
29 our $number_of_git_cmds = 0;
31 BEGIN {
32 CGI->compile() if $ENV{'MOD_PERL'};
35 our $version = "++GIT_VERSION++";
37 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
38 sub evaluate_uri {
39 our $cgi;
41 our $my_url = $cgi->url();
42 our $my_uri = $cgi->url(-absolute => 1);
44 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
45 # needed and used only for URLs with nonempty PATH_INFO
46 our $base_url = $my_url;
48 # When the script is used as DirectoryIndex, the URL does not contain the name
49 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
50 # have to do it ourselves. We make $path_info global because it's also used
51 # later on.
53 # Another issue with the script being the DirectoryIndex is that the resulting
54 # $my_url data is not the full script URL: this is good, because we want
55 # generated links to keep implying the script name if it wasn't explicitly
56 # indicated in the URL we're handling, but it means that $my_url cannot be used
57 # as base URL.
58 # Therefore, if we needed to strip PATH_INFO, then we know that we have
59 # to build the base URL ourselves:
60 our $path_info = decode_utf8($ENV{"PATH_INFO"});
61 if ($path_info) {
62 # $path_info has already been URL-decoded by the web server, but
63 # $my_url and $my_uri have not. URL-decode them so we can properly
64 # strip $path_info.
65 $my_url = unescape($my_url);
66 $my_uri = unescape($my_uri);
67 if ($my_url =~ s,\Q$path_info\E$,, &&
68 $my_uri =~ s,\Q$path_info\E$,, &&
69 defined $ENV{'SCRIPT_NAME'}) {
70 $base_url = $cgi->url(-base => 1) . $ENV{'SCRIPT_NAME'};
74 # target of the home link on top of all pages
75 our $home_link = $my_uri || "/";
78 # core git executable to use
79 # this can just be "git" if your webserver has a sensible PATH
80 our $GIT = "++GIT_BINDIR++/git";
82 # absolute fs-path which will be prepended to the project path
83 #our $projectroot = "/pub/scm";
84 our $projectroot = "++GITWEB_PROJECTROOT++";
86 # fs traversing limit for getting project list
87 # the number is relative to the projectroot
88 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
90 # string of the home link on top of all pages
91 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
93 # extra breadcrumbs preceding the home link
94 our @extra_breadcrumbs = ();
96 # name of your site or organization to appear in page titles
97 # replace this with something more descriptive for clearer bookmarks
98 our $site_name = "++GITWEB_SITENAME++"
99 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
101 # html snippet to include in the <head> section of each page
102 our $site_html_head_string = "++GITWEB_SITE_HTML_HEAD_STRING++";
103 # filename of html text to include at top of each page
104 our $site_header = "++GITWEB_SITE_HEADER++";
105 # html text to include at home page
106 our $home_text = "++GITWEB_HOMETEXT++";
107 # filename of html text to include at bottom of each page
108 our $site_footer = "++GITWEB_SITE_FOOTER++";
110 # URI of stylesheets
111 our @stylesheets = ("++GITWEB_CSS++");
112 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
113 our $stylesheet = undef;
114 # URI of GIT logo (72x27 size)
115 our $logo = "++GITWEB_LOGO++";
116 # URI of GIT favicon, assumed to be image/png type
117 our $favicon = "++GITWEB_FAVICON++";
118 # URI of gitweb.js (JavaScript code for gitweb)
119 our $javascript = "++GITWEB_JS++";
121 # URI and label (title) of GIT logo link
122 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
123 #our $logo_label = "git documentation";
124 our $logo_url = "http://git-scm.com/";
125 our $logo_label = "git homepage";
127 # source of projects list
128 our $projects_list = "++GITWEB_LIST++";
130 # the width (in characters) of the projects list "Description" column
131 our $projects_list_description_width = 25;
133 # group projects by category on the projects list
134 # (enabled if this variable evaluates to true)
135 our $projects_list_group_categories = 0;
137 # default category if none specified
138 # (leave the empty string for no category)
139 our $project_list_default_category = "";
141 # default order of projects list
142 # valid values are none, project, descr, owner, and age
143 our $default_projects_order = "project";
145 # show repository only if this file exists
146 # (only effective if this variable evaluates to true)
147 our $export_ok = "++GITWEB_EXPORT_OK++";
149 # don't generate age column on the projects list page
150 our $omit_age_column = 0;
152 # don't generate information about owners of repositories
153 our $omit_owner=0;
155 # show repository only if this subroutine returns true
156 # when given the path to the project, for example:
157 # sub { return -e "$_[0]/git-daemon-export-ok"; }
158 our $export_auth_hook = undef;
160 # only allow viewing of repositories also shown on the overview page
161 our $strict_export = "++GITWEB_STRICT_EXPORT++";
163 # list of git base URLs used for URL to where fetch project from,
164 # i.e. full URL is "$git_base_url/$project"
165 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
167 # default blob_plain mimetype and default charset for text/plain blob
168 our $default_blob_plain_mimetype = 'application/octet-stream';
169 our $default_text_plain_charset = undef;
171 # file to use for guessing MIME types before trying /etc/mime.types
172 # (relative to the current git repository)
173 our $mimetypes_file = undef;
175 # assume this charset if line contains non-UTF-8 characters;
176 # it should be valid encoding (see Encoding::Supported(3pm) for list),
177 # for which encoding all byte sequences are valid, for example
178 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
179 # could be even 'utf-8' for the old behavior)
180 our $fallback_encoding = 'latin1';
182 # rename detection options for git-diff and git-diff-tree
183 # - default is '-M', with the cost proportional to
184 # (number of removed files) * (number of new files).
185 # - more costly is '-C' (which implies '-M'), with the cost proportional to
186 # (number of changed files + number of removed files) * (number of new files)
187 # - even more costly is '-C', '--find-copies-harder' with cost
188 # (number of files in the original tree) * (number of new files)
189 # - one might want to include '-B' option, e.g. '-B', '-M'
190 our @diff_opts = ('-M'); # taken from git_commit
192 # Disables features that would allow repository owners to inject script into
193 # the gitweb domain.
194 our $prevent_xss = 0;
196 # Path to a POSIX shell. Needed to run $highlight_bin and a snapshot compressor.
197 # Only used when highlight is enabled or snapshots with compressors are enabled.
198 our $posix_shell_bin = "++POSIX_SHELL_BIN++";
200 # Path to the highlight executable to use (must be the one from
201 # http://www.andre-simon.de due to assumptions about parameters and output).
202 # Useful if highlight is not installed on your webserver's PATH.
203 # [Default: highlight]
204 our $highlight_bin = "++HIGHLIGHT_BIN++";
206 # information about snapshot formats that gitweb is capable of serving
207 our %known_snapshot_formats = (
208 # name => {
209 # 'display' => display name,
210 # 'type' => mime type,
211 # 'suffix' => filename suffix,
212 # 'format' => --format for git-archive,
213 # 'compressor' => [compressor command and arguments]
214 # (array reference, optional)
215 # 'disabled' => boolean (optional)}
217 'tgz' => {
218 'display' => 'tar.gz',
219 'type' => 'application/x-gzip',
220 'suffix' => '.tar.gz',
221 'format' => 'tar',
222 'compressor' => ['gzip', '-n']},
224 'tbz2' => {
225 'display' => 'tar.bz2',
226 'type' => 'application/x-bzip2',
227 'suffix' => '.tar.bz2',
228 'format' => 'tar',
229 'compressor' => ['bzip2']},
231 'txz' => {
232 'display' => 'tar.xz',
233 'type' => 'application/x-xz',
234 'suffix' => '.tar.xz',
235 'format' => 'tar',
236 'compressor' => ['xz'],
237 'disabled' => 1},
239 'zip' => {
240 'display' => 'zip',
241 'type' => 'application/x-zip',
242 'suffix' => '.zip',
243 'format' => 'zip'},
246 # Aliases so we understand old gitweb.snapshot values in repository
247 # configuration.
248 our %known_snapshot_format_aliases = (
249 'gzip' => 'tgz',
250 'bzip2' => 'tbz2',
251 'xz' => 'txz',
253 # backward compatibility: legacy gitweb config support
254 'x-gzip' => undef, 'gz' => undef,
255 'x-bzip2' => undef, 'bz2' => undef,
256 'x-zip' => undef, '' => undef,
259 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
260 # are changed, it may be appropriate to change these values too via
261 # $GITWEB_CONFIG.
262 our %avatar_size = (
263 'default' => 16,
264 'double' => 32
267 # Used to set the maximum load that we will still respond to gitweb queries.
268 # If server load exceed this value then return "503 server busy" error.
269 # If gitweb cannot determined server load, it is taken to be 0.
270 # Leave it undefined (or set to 'undef') to turn off load checking.
271 our $maxload = 300;
273 # configuration for 'highlight' (http://www.andre-simon.de/)
274 # match by basename
275 our %highlight_basename = (
276 #'Program' => 'py',
277 #'Library' => 'py',
278 'SConstruct' => 'py', # SCons equivalent of Makefile
279 'Makefile' => 'make',
280 'makefile' => 'make',
281 'GNUmakefile' => 'make',
282 'BSDmakefile' => 'make',
284 # match by shebang regex
285 our %highlight_shebang = (
286 # Each entry has a key which is the syntax to use and
287 # a value which is either a qr regex or an array of qr regexs to match
288 # against the first 128 (less if the blob is shorter) BYTES of the blob.
289 # We match /usr/bin/env items separately to require "/usr/bin/env" and
290 # allow a limited subset of NAME=value items to appear.
291 'awk' => [ qr,^#!\s*/(?:\w+/)*(?:[gnm]?awk)(?:\s|$),mo,
292 qr,^#!\s*/usr/bin/env\s+(?:\w+=\w*\s+)*(?:[gnm]?awk)(?:\s|$),mo ],
293 'make' => [ qr,^#!\s*/(?:\w+/)*(?:g?make)(?:\s|$),mo,
294 qr,^#!\s*/usr/bin/env\s+(?:\w+=\w*\s+)*(?:g?make)(?:\s|$),mo ],
295 'php' => [ qr,^#!\s*/(?:\w+/)*(?:php)(?:\s|$),mo,
296 qr,^#!\s*/usr/bin/env\s+(?:\w+=\w*\s+)*(?:php)(?:\s|$),mo ],
297 'pl' => [ qr,^#!\s*/(?:\w+/)*(?:perl)(?:\s|$),mo,
298 qr,^#!\s*/usr/bin/env\s+(?:\w+=\w*\s+)*(?:perl)(?:\s|$),mo ],
299 'py' => [ qr,^#!\s*/(?:\w+/)*(?:python)(?:\s|$),mo,
300 qr,^#!\s*/usr/bin/env\s+(?:\w+=\w*\s+)*(?:python)(?:\s|$),mo ],
301 'sh' => [ qr,^#!\s*/(?:\w+/)*(?:[bd]ash|t?csh|[akz]?sh)(?:\s|$),mo,
302 qr,^#!\s*/usr/bin/env\s+(?:\w+=\w*\s+)*(?:[bd]ash|t?csh|[akz]?sh)(?:\s|$),mo ],
303 'rb' => [ qr,^#!\s*/(?:\w+/)*(?:perl)(?:\s|$),mo,
304 qr,^#!\s*/usr/bin/env\s+(?:\w+=\w*\s+)*(?:perl)(?:\s|$),mo ],
306 # match by extension
307 our %highlight_ext = (
308 # main extensions, defining name of syntax;
309 # see files in /usr/share/highlight/langDefs/ directory
310 (map { $_ => $_ } qw(
311 4gl a4c abnf abp ada agda ahk ampl amtrix applescript arc
312 arm as asm asp aspect ats au3 avenue awk bat bb bbcode bib
313 bms bnf boo c cb cfc chl clipper clojure clp cob cs css d
314 diff dot dylan e ebnf erl euphoria exp f90 flx for frink fs
315 go haskell hcl html httpd hx icl icn idl idlang ili
316 inc_luatex ini inp io iss j java js jsp lbn ldif lgt lhs
317 lisp lotos ls lsl lua ly make mel mercury mib miranda ml mo
318 mod2 mod3 mpl ms mssql n nas nbc nice nrx nsi nut nxc oberon
319 objc octave oorexx os oz pas php pike pl pl1 pov pro
320 progress ps ps1 psl pure py pyx q qmake qu r rb rebol rexx
321 rnc s sas sc scala scilab sh sma smalltalk sml sno spec spn
322 sql sybase tcl tcsh tex ttcn3 vala vb verilog vhd xml xpp y
323 yaiff znn)),
324 # alternate extensions, see /etc/highlight/filetypes.conf
325 (map { $_ => '4gl' } qw(informix)),
326 (map { $_ => 'a4c' } qw(ascend)),
327 (map { $_ => 'abp' } qw(abp4)),
328 (map { $_ => 'ada' } qw(a adb ads gnad)),
329 (map { $_ => 'ahk' } qw(autohotkey)),
330 (map { $_ => 'ampl' } qw(dat run)),
331 (map { $_ => 'amtrix' } qw(hnd s4 s4h s4t t4)),
332 (map { $_ => 'as' } qw(actionscript)),
333 (map { $_ => 'asm' } qw(29k 68s 68x a51 assembler x68 x86)),
334 (map { $_ => 'asp' } qw(asa)),
335 (map { $_ => 'aspect' } qw(was wud)),
336 (map { $_ => 'ats' } qw(dats)),
337 (map { $_ => 'au3' } qw(autoit)),
338 (map { $_ => 'bat' } qw(cmd)),
339 (map { $_ => 'bb' } qw(blitzbasic)),
340 (map { $_ => 'bib' } qw(bibtex)),
341 (map { $_ => 'c' } qw(c++ cc cpp cu cxx h hh hpp hxx)),
342 (map { $_ => 'cb' } qw(clearbasic)),
343 (map { $_ => 'cfc' } qw(cfm coldfusion)),
344 (map { $_ => 'chl' } qw(chill)),
345 (map { $_ => 'cob' } qw(cbl cobol)),
346 (map { $_ => 'cs' } qw(csharp)),
347 (map { $_ => 'diff' } qw(patch)),
348 (map { $_ => 'dot' } qw(graphviz)),
349 (map { $_ => 'e' } qw(eiffel se)),
350 (map { $_ => 'erl' } qw(erlang hrl)),
351 (map { $_ => 'euphoria' } qw(eu ew ex exu exw wxu)),
352 (map { $_ => 'exp' } qw(express)),
353 (map { $_ => 'f90' } qw(f95)),
354 (map { $_ => 'flx' } qw(felix)),
355 (map { $_ => 'for' } qw(f f77 ftn)),
356 (map { $_ => 'fs' } qw(fsharp fsx)),
357 (map { $_ => 'haskell' } qw(hs)),
358 (map { $_ => 'html' } qw(htm xhtml)),
359 (map { $_ => 'hx' } qw(haxe)),
360 (map { $_ => 'icl' } qw(clean)),
361 (map { $_ => 'icn' } qw(icon)),
362 (map { $_ => 'ili' } qw(interlis)),
363 (map { $_ => 'inp' } qw(fame)),
364 (map { $_ => 'iss' } qw(innosetup)),
365 (map { $_ => 'j' } qw(jasmin)),
366 (map { $_ => 'java' } qw(groovy grv)),
367 (map { $_ => 'lbn' } qw(luban)),
368 (map { $_ => 'lgt' } qw(logtalk)),
369 (map { $_ => 'lisp' } qw(cl clisp el lsp sbcl scom)),
370 (map { $_ => 'ls' } qw(lotus)),
371 (map { $_ => 'lsl' } qw(lindenscript)),
372 (map { $_ => 'ly' } qw(lilypond)),
373 (map { $_ => 'make' } qw(mak mk kmk)),
374 (map { $_ => 'mel' } qw(maya)),
375 (map { $_ => 'mib' } qw(smi snmp)),
376 (map { $_ => 'ml' } qw(mli ocaml)),
377 (map { $_ => 'mo' } qw(modelica)),
378 (map { $_ => 'mod2' } qw(def mod)),
379 (map { $_ => 'mod3' } qw(i3 m3)),
380 (map { $_ => 'mpl' } qw(maple)),
381 (map { $_ => 'n' } qw(nemerle)),
382 (map { $_ => 'nas' } qw(nasal)),
383 (map { $_ => 'nrx' } qw(netrexx)),
384 (map { $_ => 'nsi' } qw(nsis)),
385 (map { $_ => 'nut' } qw(squirrel)),
386 (map { $_ => 'oberon' } qw(ooc)),
387 (map { $_ => 'objc' } qw(M m mm)),
388 (map { $_ => 'php' } qw(php3 php4 php5 php6)),
389 (map { $_ => 'pike' } qw(pmod)),
390 (map { $_ => 'pl' } qw(perl plex plx pm)),
391 (map { $_ => 'pl1' } qw(bdy ff fp fpp rpp sf sp spb spe spp sps wf wp wpb wpp wps)),
392 (map { $_ => 'progress' } qw(i p w)),
393 (map { $_ => 'py' } qw(python)),
394 (map { $_ => 'pyx' } qw(pyrex)),
395 (map { $_ => 'rb' } qw(pp rjs ruby)),
396 (map { $_ => 'rexx' } qw(rex rx the)),
397 (map { $_ => 'sc' } qw(paradox)),
398 (map { $_ => 'scilab' } qw(sce sci)),
399 (map { $_ => 'sh' } qw(bash ebuild eclass ksh zsh)),
400 (map { $_ => 'sma' } qw(small)),
401 (map { $_ => 'smalltalk' } qw(gst sq st)),
402 (map { $_ => 'sno' } qw(snobal)),
403 (map { $_ => 'sybase' } qw(sp)),
404 (map { $_ => 'tcl' } qw(itcl wish)),
405 (map { $_ => 'tex' } qw(cls sty)),
406 (map { $_ => 'vb' } qw(bas basic bi vbs)),
407 (map { $_ => 'verilog' } qw(v)),
408 (map { $_ => 'xml' } qw(dtd ecf ent hdr hub jnlp nrm plist resx sgm sgml svg tld vxml wml xsd xsl)),
409 (map { $_ => 'y' } qw(bison)),
412 # You define site-wide feature defaults here; override them with
413 # $GITWEB_CONFIG as necessary.
414 our %feature = (
415 # feature => {
416 # 'sub' => feature-sub (subroutine),
417 # 'override' => allow-override (boolean),
418 # 'default' => [ default options...] (array reference)}
420 # if feature is overridable (it means that allow-override has true value),
421 # then feature-sub will be called with default options as parameters;
422 # return value of feature-sub indicates if to enable specified feature
424 # if there is no 'sub' key (no feature-sub), then feature cannot be
425 # overridden
427 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
428 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
429 # is enabled
431 # Enable the 'blame' blob view, showing the last commit that modified
432 # each line in the file. This can be very CPU-intensive.
434 # To enable system wide have in $GITWEB_CONFIG
435 # $feature{'blame'}{'default'} = [1];
436 # To have project specific config enable override in $GITWEB_CONFIG
437 # $feature{'blame'}{'override'} = 1;
438 # and in project config gitweb.blame = 0|1;
439 'blame' => {
440 'sub' => sub { feature_bool('blame', @_) },
441 'override' => 0,
442 'default' => [0]},
444 # Enable the 'snapshot' link, providing a compressed archive of any
445 # tree. This can potentially generate high traffic if you have large
446 # project.
448 # Value is a list of formats defined in %known_snapshot_formats that
449 # you wish to offer.
450 # To disable system wide have in $GITWEB_CONFIG
451 # $feature{'snapshot'}{'default'} = [];
452 # To have project specific config enable override in $GITWEB_CONFIG
453 # $feature{'snapshot'}{'override'} = 1;
454 # and in project config, a comma-separated list of formats or "none"
455 # to disable. Example: gitweb.snapshot = tbz2,zip;
456 'snapshot' => {
457 'sub' => \&feature_snapshot,
458 'override' => 0,
459 'default' => ['tgz']},
461 # Enable text search, which will list the commits which match author,
462 # committer or commit text to a given string. Enabled by default.
463 # Project specific override is not supported.
465 # Note that this controls all search features, which means that if
466 # it is disabled, then 'grep' and 'pickaxe' search would also be
467 # disabled.
468 'search' => {
469 'override' => 0,
470 'default' => [1]},
472 # Enable grep search, which will list the files in currently selected
473 # tree containing the given string. Enabled by default. This can be
474 # potentially CPU-intensive, of course.
475 # Note that you need to have 'search' feature enabled too.
477 # To enable system wide have in $GITWEB_CONFIG
478 # $feature{'grep'}{'default'} = [1];
479 # To have project specific config enable override in $GITWEB_CONFIG
480 # $feature{'grep'}{'override'} = 1;
481 # and in project config gitweb.grep = 0|1;
482 'grep' => {
483 'sub' => sub { feature_bool('grep', @_) },
484 'override' => 0,
485 'default' => [1]},
487 # Enable the pickaxe search, which will list the commits that modified
488 # a given string in a file. This can be practical and quite faster
489 # alternative to 'blame', but still potentially CPU-intensive.
490 # Note that you need to have 'search' feature enabled too.
492 # To enable system wide have in $GITWEB_CONFIG
493 # $feature{'pickaxe'}{'default'} = [1];
494 # To have project specific config enable override in $GITWEB_CONFIG
495 # $feature{'pickaxe'}{'override'} = 1;
496 # and in project config gitweb.pickaxe = 0|1;
497 'pickaxe' => {
498 'sub' => sub { feature_bool('pickaxe', @_) },
499 'override' => 0,
500 'default' => [1]},
502 # Enable showing size of blobs in a 'tree' view, in a separate
503 # column, similar to what 'ls -l' does. This cost a bit of IO.
505 # To disable system wide have in $GITWEB_CONFIG
506 # $feature{'show-sizes'}{'default'} = [0];
507 # To have project specific config enable override in $GITWEB_CONFIG
508 # $feature{'show-sizes'}{'override'} = 1;
509 # and in project config gitweb.showsizes = 0|1;
510 'show-sizes' => {
511 'sub' => sub { feature_bool('showsizes', @_) },
512 'override' => 0,
513 'default' => [1]},
515 # Make gitweb use an alternative format of the URLs which can be
516 # more readable and natural-looking: project name is embedded
517 # directly in the path and the query string contains other
518 # auxiliary information. All gitweb installations recognize
519 # URL in either format; this configures in which formats gitweb
520 # generates links.
522 # To enable system wide have in $GITWEB_CONFIG
523 # $feature{'pathinfo'}{'default'} = [1];
524 # Project specific override is not supported.
526 # Note that you will need to change the default location of CSS,
527 # favicon, logo and possibly other files to an absolute URL. Also,
528 # if gitweb.cgi serves as your indexfile, you will need to force
529 # $my_uri to contain the script name in your $GITWEB_CONFIG (and you
530 # will also likely want to set $home_link if you're setting $my_uri).
531 'pathinfo' => {
532 'override' => 0,
533 'default' => [0]},
535 # Make gitweb consider projects in project root subdirectories
536 # to be forks of existing projects. Given project $projname.git,
537 # projects matching $projname/*.git will not be shown in the main
538 # projects list, instead a '+' mark will be added to $projname
539 # there and a 'forks' view will be enabled for the project, listing
540 # all the forks. If project list is taken from a file, forks have
541 # to be listed after the main project.
543 # To enable system wide have in $GITWEB_CONFIG
544 # $feature{'forks'}{'default'} = [1];
545 # Project specific override is not supported.
546 'forks' => {
547 'override' => 0,
548 'default' => [0]},
550 # Insert custom links to the action bar of all project pages.
551 # This enables you mainly to link to third-party scripts integrating
552 # into gitweb; e.g. git-browser for graphical history representation
553 # or custom web-based repository administration interface.
555 # The 'default' value consists of a list of triplets in the form
556 # (label, link, position) where position is the label after which
557 # to insert the link and link is a format string where %n expands
558 # to the project name, %f to the project path within the filesystem,
559 # %h to the current hash (h gitweb parameter) and %b to the current
560 # hash base (hb gitweb parameter); %% expands to %.
562 # To enable system wide have in $GITWEB_CONFIG e.g.
563 # $feature{'actions'}{'default'} = [('graphiclog',
564 # '/git-browser/by-commit.html?r=%n', 'summary')];
565 # Project specific override is not supported.
566 'actions' => {
567 'override' => 0,
568 'default' => []},
570 # Allow gitweb scan project content tags of project repository,
571 # and display the popular Web 2.0-ish "tag cloud" near the projects
572 # list. Note that this is something COMPLETELY different from the
573 # normal Git tags.
575 # gitweb by itself can show existing tags, but it does not handle
576 # tagging itself; you need to do it externally, outside gitweb.
577 # The format is described in git_get_project_ctags() subroutine.
578 # You may want to install the HTML::TagCloud Perl module to get
579 # a pretty tag cloud instead of just a list of tags.
581 # To enable system wide have in $GITWEB_CONFIG
582 # $feature{'ctags'}{'default'} = [1];
583 # Project specific override is not supported.
585 # In the future whether ctags editing is enabled might depend
586 # on the value, but using 1 should always mean no editing of ctags.
587 'ctags' => {
588 'override' => 0,
589 'default' => [0]},
591 # The maximum number of patches in a patchset generated in patch
592 # view. Set this to 0 or undef to disable patch view, or to a
593 # negative number to remove any limit.
595 # To disable system wide have in $GITWEB_CONFIG
596 # $feature{'patches'}{'default'} = [0];
597 # To have project specific config enable override in $GITWEB_CONFIG
598 # $feature{'patches'}{'override'} = 1;
599 # and in project config gitweb.patches = 0|n;
600 # where n is the maximum number of patches allowed in a patchset.
601 'patches' => {
602 'sub' => \&feature_patches,
603 'override' => 0,
604 'default' => [16]},
606 # Avatar support. When this feature is enabled, views such as
607 # shortlog or commit will display an avatar associated with
608 # the email of the committer(s) and/or author(s).
610 # Currently available providers are gravatar and picon.
611 # If an unknown provider is specified, the feature is disabled.
613 # Gravatar depends on Digest::MD5.
614 # Picon currently relies on the indiana.edu database.
616 # To enable system wide have in $GITWEB_CONFIG
617 # $feature{'avatar'}{'default'} = ['<provider>'];
618 # where <provider> is either gravatar or picon.
619 # To have project specific config enable override in $GITWEB_CONFIG
620 # $feature{'avatar'}{'override'} = 1;
621 # and in project config gitweb.avatar = <provider>;
622 'avatar' => {
623 'sub' => \&feature_avatar,
624 'override' => 0,
625 'default' => ['']},
627 # Enable displaying how much time and how many git commands
628 # it took to generate and display page. Disabled by default.
629 # Project specific override is not supported.
630 'timed' => {
631 'override' => 0,
632 'default' => [0]},
634 # Enable turning some links into links to actions which require
635 # JavaScript to run (like 'blame_incremental'). Not enabled by
636 # default. Project specific override is currently not supported.
637 'javascript-actions' => {
638 'override' => 0,
639 'default' => [0]},
641 # Enable and configure ability to change common timezone for dates
642 # in gitweb output via JavaScript. Enabled by default.
643 # Project specific override is not supported.
644 'javascript-timezone' => {
645 'override' => 0,
646 'default' => [
647 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
648 # or undef to turn off this feature
649 'gitweb_tz', # name of cookie where to store selected timezone
650 'datetime', # CSS class used to mark up dates for manipulation
653 # Syntax highlighting support. This is based on Daniel Svensson's
654 # and Sham Chukoury's work in gitweb-xmms2.git.
655 # It requires the 'highlight' program present in $PATH,
656 # and therefore is disabled by default.
658 # To enable system wide have in $GITWEB_CONFIG
659 # $feature{'highlight'}{'default'} = [1];
661 'highlight' => {
662 'sub' => sub { feature_bool('highlight', @_) },
663 'override' => 0,
664 'default' => [0]},
666 # Enable displaying of remote heads in the heads list
668 # To enable system wide have in $GITWEB_CONFIG
669 # $feature{'remote_heads'}{'default'} = [1];
670 # To have project specific config enable override in $GITWEB_CONFIG
671 # $feature{'remote_heads'}{'override'} = 1;
672 # and in project config gitweb.remoteheads = 0|1;
673 'remote_heads' => {
674 'sub' => sub { feature_bool('remote_heads', @_) },
675 'override' => 0,
676 'default' => [0]},
678 # Enable showing branches under other refs in addition to heads
680 # To set system wide extra branch refs have in $GITWEB_CONFIG
681 # $feature{'extra-branch-refs'}{'default'} = ['dirs', 'of', 'choice'];
682 # To have project specific config enable override in $GITWEB_CONFIG
683 # $feature{'extra-branch-refs'}{'override'} = 1;
684 # and in project config gitweb.extrabranchrefs = dirs of choice
685 # Every directory is separated with whitespace.
687 'extra-branch-refs' => {
688 'sub' => \&feature_extra_branch_refs,
689 'override' => 0,
690 'default' => []},
693 sub gitweb_get_feature {
694 my ($name) = @_;
695 return unless exists $feature{$name};
696 my ($sub, $override, @defaults) = (
697 $feature{$name}{'sub'},
698 $feature{$name}{'override'},
699 @{$feature{$name}{'default'}});
700 # project specific override is possible only if we have project
701 our $git_dir; # global variable, declared later
702 if (!$override || !defined $git_dir) {
703 return @defaults;
705 if (!defined $sub) {
706 warn "feature $name is not overridable";
707 return @defaults;
709 return $sub->(@defaults);
712 # A wrapper to check if a given feature is enabled.
713 # With this, you can say
715 # my $bool_feat = gitweb_check_feature('bool_feat');
716 # gitweb_check_feature('bool_feat') or somecode;
718 # instead of
720 # my ($bool_feat) = gitweb_get_feature('bool_feat');
721 # (gitweb_get_feature('bool_feat'))[0] or somecode;
723 sub gitweb_check_feature {
724 return (gitweb_get_feature(@_))[0];
728 sub feature_bool {
729 my $key = shift;
730 my ($val) = git_get_project_config($key, '--bool');
732 if (!defined $val) {
733 return ($_[0]);
734 } elsif ($val eq 'true') {
735 return (1);
736 } elsif ($val eq 'false') {
737 return (0);
741 sub feature_snapshot {
742 my (@fmts) = @_;
744 my ($val) = git_get_project_config('snapshot');
746 if ($val) {
747 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
750 return @fmts;
753 sub feature_patches {
754 my @val = (git_get_project_config('patches', '--int'));
756 if (@val) {
757 return @val;
760 return ($_[0]);
763 sub feature_avatar {
764 my @val = (git_get_project_config('avatar'));
766 return @val ? @val : @_;
769 sub feature_extra_branch_refs {
770 my (@branch_refs) = @_;
771 my $values = git_get_project_config('extrabranchrefs');
773 if ($values) {
774 $values = config_to_multi ($values);
775 @branch_refs = ();
776 foreach my $value (@{$values}) {
777 push @branch_refs, split /\s+/, $value;
781 return @branch_refs;
784 # checking HEAD file with -e is fragile if the repository was
785 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
786 # and then pruned.
787 sub check_head_link {
788 my ($dir) = @_;
789 my $headfile = "$dir/HEAD";
790 return ((-e $headfile) ||
791 (-l $headfile && readlink($headfile) =~ /^refs\/heads\//));
794 sub check_export_ok {
795 my ($dir) = @_;
796 return (check_head_link($dir) &&
797 (!$export_ok || -e "$dir/$export_ok") &&
798 (!$export_auth_hook || $export_auth_hook->($dir)));
801 # process alternate names for backward compatibility
802 # filter out unsupported (unknown) snapshot formats
803 sub filter_snapshot_fmts {
804 my @fmts = @_;
806 @fmts = map {
807 exists $known_snapshot_format_aliases{$_} ?
808 $known_snapshot_format_aliases{$_} : $_} @fmts;
809 @fmts = grep {
810 exists $known_snapshot_formats{$_} &&
811 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
814 sub filter_and_validate_refs {
815 my @refs = @_;
816 my %unique_refs = ();
818 foreach my $ref (@refs) {
819 die_error(500, "Invalid ref '$ref' in 'extra-branch-refs' feature") unless (is_valid_ref_format($ref));
820 # 'heads' are added implicitly in get_branch_refs().
821 $unique_refs{$ref} = 1 if ($ref ne 'heads');
823 return sort keys %unique_refs;
826 # If it is set to code reference, it is code that it is to be run once per
827 # request, allowing updating configurations that change with each request,
828 # while running other code in config file only once.
830 # Otherwise, if it is false then gitweb would process config file only once;
831 # if it is true then gitweb config would be run for each request.
832 our $per_request_config = 1;
834 # If true and fileno STDIN is 0 and getsockname succeeds and getpeername fails
835 # with ENOTCONN, then FCGI mode will be activated automatically in just the
836 # same way as though the --fcgi option had been given instead.
837 our $auto_fcgi = 0;
839 # read and parse gitweb config file given by its parameter.
840 # returns true on success, false on recoverable error, allowing
841 # to chain this subroutine, using first file that exists.
842 # dies on errors during parsing config file, as it is unrecoverable.
843 sub read_config_file {
844 my $filename = shift;
845 return unless defined $filename;
846 # die if there are errors parsing config file
847 if (-e $filename) {
848 do $filename;
849 die $@ if $@;
850 return 1;
852 return;
855 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
856 sub evaluate_gitweb_config {
857 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
858 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
859 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "++GITWEB_CONFIG_COMMON++";
861 # Protect against duplications of file names, to not read config twice.
862 # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
863 # there possibility of duplication of filename there doesn't matter.
864 $GITWEB_CONFIG = "" if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
865 $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
867 # Common system-wide settings for convenience.
868 # Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
869 read_config_file($GITWEB_CONFIG_COMMON);
871 # Use first config file that exists. This means use the per-instance
872 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
873 read_config_file($GITWEB_CONFIG) and return;
874 read_config_file($GITWEB_CONFIG_SYSTEM);
877 # Get loadavg of system, to compare against $maxload.
878 # Currently it requires '/proc/loadavg' present to get loadavg;
879 # if it is not present it returns 0, which means no load checking.
880 sub get_loadavg {
881 if( -e '/proc/loadavg' ){
882 open my $fd, '<', '/proc/loadavg'
883 or return 0;
884 my @load = split(/\s+/, scalar <$fd>);
885 close $fd;
887 # The first three columns measure CPU and IO utilization of the last one,
888 # five, and 10 minute periods. The fourth column shows the number of
889 # currently running processes and the total number of processes in the m/n
890 # format. The last column displays the last process ID used.
891 return $load[0] || 0;
893 # additional checks for load average should go here for things that don't export
894 # /proc/loadavg
896 return 0;
899 # version of the core git binary
900 our $git_version;
901 sub evaluate_git_version {
902 our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
903 $number_of_git_cmds++;
906 sub check_loadavg {
907 if (defined $maxload && get_loadavg() > $maxload) {
908 die_error(503, "The load average on the server is too high");
912 # ======================================================================
913 # input validation and dispatch
915 # input parameters can be collected from a variety of sources (presently, CGI
916 # and PATH_INFO), so we define an %input_params hash that collects them all
917 # together during validation: this allows subsequent uses (e.g. href()) to be
918 # agnostic of the parameter origin
920 our %input_params = ();
922 # input parameters are stored with the long parameter name as key. This will
923 # also be used in the href subroutine to convert parameters to their CGI
924 # equivalent, and since the href() usage is the most frequent one, we store
925 # the name -> CGI key mapping here, instead of the reverse.
927 # XXX: Warning: If you touch this, check the search form for updating,
928 # too.
930 our @cgi_param_mapping = (
931 project => "p",
932 action => "a",
933 file_name => "f",
934 file_parent => "fp",
935 hash => "h",
936 hash_parent => "hp",
937 hash_base => "hb",
938 hash_parent_base => "hpb",
939 page => "pg",
940 order => "o",
941 searchtext => "s",
942 searchtype => "st",
943 snapshot_format => "sf",
944 extra_options => "opt",
945 search_use_regexp => "sr",
946 ctag => "by_tag",
947 diff_style => "ds",
948 project_filter => "pf",
949 # this must be last entry (for manipulation from JavaScript)
950 javascript => "js"
952 our %cgi_param_mapping = @cgi_param_mapping;
954 # we will also need to know the possible actions, for validation
955 our %actions = (
956 "blame" => \&git_blame,
957 "blame_incremental" => \&git_blame_incremental,
958 "blame_data" => \&git_blame_data,
959 "blobdiff" => \&git_blobdiff,
960 "blobdiff_plain" => \&git_blobdiff_plain,
961 "blob" => \&git_blob,
962 "blob_plain" => \&git_blob_plain,
963 "commitdiff" => \&git_commitdiff,
964 "commitdiff_plain" => \&git_commitdiff_plain,
965 "commit" => \&git_commit,
966 "forks" => \&git_forks,
967 "heads" => \&git_heads,
968 "history" => \&git_history,
969 "log" => \&git_log,
970 "patch" => \&git_patch,
971 "patches" => \&git_patches,
972 "remotes" => \&git_remotes,
973 "rss" => \&git_rss,
974 "atom" => \&git_atom,
975 "search" => \&git_search,
976 "search_help" => \&git_search_help,
977 "shortlog" => \&git_shortlog,
978 "summary" => \&git_summary,
979 "tag" => \&git_tag,
980 "tags" => \&git_tags,
981 "tree" => \&git_tree,
982 "snapshot" => \&git_snapshot,
983 "object" => \&git_object,
984 # those below don't need $project
985 "opml" => \&git_opml,
986 "project_list" => \&git_project_list,
987 "project_index" => \&git_project_index,
990 # finally, we have the hash of allowed extra_options for the commands that
991 # allow them
992 our %allowed_options = (
993 "--no-merges" => [ qw(rss atom log shortlog history) ],
996 # fill %input_params with the CGI parameters. All values except for 'opt'
997 # should be single values, but opt can be an array. We should probably
998 # build an array of parameters that can be multi-valued, but since for the time
999 # being it's only this one, we just single it out
1000 sub evaluate_query_params {
1001 our $cgi;
1003 while (my ($name, $symbol) = each %cgi_param_mapping) {
1004 if ($symbol eq 'opt') {
1005 $input_params{$name} = [ map { decode_utf8($_) } $cgi->multi_param($symbol) ];
1006 } else {
1007 $input_params{$name} = decode_utf8($cgi->param($symbol));
1012 # now read PATH_INFO and update the parameter list for missing parameters
1013 sub evaluate_path_info {
1014 return if defined $input_params{'project'};
1015 return if !$path_info;
1016 $path_info =~ s,^/+,,;
1017 return if !$path_info;
1019 # find which part of PATH_INFO is project
1020 my $project = $path_info;
1021 $project =~ s,/+$,,;
1022 while ($project && !check_head_link("$projectroot/$project")) {
1023 $project =~ s,/*[^/]*$,,;
1025 return unless $project;
1026 $input_params{'project'} = $project;
1028 # do not change any parameters if an action is given using the query string
1029 return if $input_params{'action'};
1030 $path_info =~ s,^\Q$project\E/*,,;
1032 # next, check if we have an action
1033 my $action = $path_info;
1034 $action =~ s,/.*$,,;
1035 if (exists $actions{$action}) {
1036 $path_info =~ s,^$action/*,,;
1037 $input_params{'action'} = $action;
1040 # list of actions that want hash_base instead of hash, but can have no
1041 # pathname (f) parameter
1042 my @wants_base = (
1043 'tree',
1044 'history',
1047 # we want to catch, among others
1048 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
1049 my ($parentrefname, $parentpathname, $refname, $pathname) =
1050 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
1052 # first, analyze the 'current' part
1053 if (defined $pathname) {
1054 # we got "branch:filename" or "branch:dir/"
1055 # we could use git_get_type(branch:pathname), but:
1056 # - it needs $git_dir
1057 # - it does a git() call
1058 # - the convention of terminating directories with a slash
1059 # makes it superfluous
1060 # - embedding the action in the PATH_INFO would make it even
1061 # more superfluous
1062 $pathname =~ s,^/+,,;
1063 if (!$pathname || substr($pathname, -1) eq "/") {
1064 $input_params{'action'} ||= "tree";
1065 $pathname =~ s,/$,,;
1066 } else {
1067 # the default action depends on whether we had parent info
1068 # or not
1069 if ($parentrefname) {
1070 $input_params{'action'} ||= "blobdiff_plain";
1071 } else {
1072 $input_params{'action'} ||= "blob_plain";
1075 $input_params{'hash_base'} ||= $refname;
1076 $input_params{'file_name'} ||= $pathname;
1077 } elsif (defined $refname) {
1078 # we got "branch". In this case we have to choose if we have to
1079 # set hash or hash_base.
1081 # Most of the actions without a pathname only want hash to be
1082 # set, except for the ones specified in @wants_base that want
1083 # hash_base instead. It should also be noted that hand-crafted
1084 # links having 'history' as an action and no pathname or hash
1085 # set will fail, but that happens regardless of PATH_INFO.
1086 if (defined $parentrefname) {
1087 # if there is parent let the default be 'shortlog' action
1088 # (for http://git.example.com/repo.git/A..B links); if there
1089 # is no parent, dispatch will detect type of object and set
1090 # action appropriately if required (if action is not set)
1091 $input_params{'action'} ||= "shortlog";
1093 if ($input_params{'action'} &&
1094 grep { $_ eq $input_params{'action'} } @wants_base) {
1095 $input_params{'hash_base'} ||= $refname;
1096 } else {
1097 $input_params{'hash'} ||= $refname;
1101 # next, handle the 'parent' part, if present
1102 if (defined $parentrefname) {
1103 # a missing pathspec defaults to the 'current' filename, allowing e.g.
1104 # someproject/blobdiff/oldrev..newrev:/filename
1105 if ($parentpathname) {
1106 $parentpathname =~ s,^/+,,;
1107 $parentpathname =~ s,/$,,;
1108 $input_params{'file_parent'} ||= $parentpathname;
1109 } else {
1110 $input_params{'file_parent'} ||= $input_params{'file_name'};
1112 # we assume that hash_parent_base is wanted if a path was specified,
1113 # or if the action wants hash_base instead of hash
1114 if (defined $input_params{'file_parent'} ||
1115 grep { $_ eq $input_params{'action'} } @wants_base) {
1116 $input_params{'hash_parent_base'} ||= $parentrefname;
1117 } else {
1118 $input_params{'hash_parent'} ||= $parentrefname;
1122 # for the snapshot action, we allow URLs in the form
1123 # $project/snapshot/$hash.ext
1124 # where .ext determines the snapshot and gets removed from the
1125 # passed $refname to provide the $hash.
1127 # To be able to tell that $refname includes the format extension, we
1128 # require the following two conditions to be satisfied:
1129 # - the hash input parameter MUST have been set from the $refname part
1130 # of the URL (i.e. they must be equal)
1131 # - the snapshot format MUST NOT have been defined already (e.g. from
1132 # CGI parameter sf)
1133 # It's also useless to try any matching unless $refname has a dot,
1134 # so we check for that too
1135 if (defined $input_params{'action'} &&
1136 $input_params{'action'} eq 'snapshot' &&
1137 defined $refname && index($refname, '.') != -1 &&
1138 $refname eq $input_params{'hash'} &&
1139 !defined $input_params{'snapshot_format'}) {
1140 # We loop over the known snapshot formats, checking for
1141 # extensions. Allowed extensions are both the defined suffix
1142 # (which includes the initial dot already) and the snapshot
1143 # format key itself, with a prepended dot
1144 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1145 my $hash = $refname;
1146 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1147 next;
1149 my $sfx = $1;
1150 # a valid suffix was found, so set the snapshot format
1151 # and reset the hash parameter
1152 $input_params{'snapshot_format'} = $fmt;
1153 $input_params{'hash'} = $hash;
1154 # we also set the format suffix to the one requested
1155 # in the URL: this way a request for e.g. .tgz returns
1156 # a .tgz instead of a .tar.gz
1157 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1158 last;
1163 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1164 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1165 $searchtext, $search_regexp, $project_filter);
1166 sub evaluate_and_validate_params {
1167 our $action = $input_params{'action'};
1168 if (defined $action) {
1169 if (!is_valid_action($action)) {
1170 die_error(400, "Invalid action parameter");
1174 # parameters which are pathnames
1175 our $project = $input_params{'project'};
1176 if (defined $project) {
1177 if (!is_valid_project($project)) {
1178 undef $project;
1179 die_error(404, "No such project");
1183 our $project_filter = $input_params{'project_filter'};
1184 if (defined $project_filter) {
1185 if (!is_valid_pathname($project_filter)) {
1186 die_error(404, "Invalid project_filter parameter");
1190 our $file_name = $input_params{'file_name'};
1191 if (defined $file_name) {
1192 if (!is_valid_pathname($file_name)) {
1193 die_error(400, "Invalid file parameter");
1197 our $file_parent = $input_params{'file_parent'};
1198 if (defined $file_parent) {
1199 if (!is_valid_pathname($file_parent)) {
1200 die_error(400, "Invalid file parent parameter");
1204 # parameters which are refnames
1205 our $hash = $input_params{'hash'};
1206 if (defined $hash) {
1207 if (!is_valid_refname($hash)) {
1208 die_error(400, "Invalid hash parameter");
1212 our $hash_parent = $input_params{'hash_parent'};
1213 if (defined $hash_parent) {
1214 if (!is_valid_refname($hash_parent)) {
1215 die_error(400, "Invalid hash parent parameter");
1219 our $hash_base = $input_params{'hash_base'};
1220 if (defined $hash_base) {
1221 if (!is_valid_refname($hash_base)) {
1222 die_error(400, "Invalid hash base parameter");
1226 our @extra_options = @{$input_params{'extra_options'}};
1227 # @extra_options is always defined, since it can only be (currently) set from
1228 # CGI, and $cgi->param() returns the empty array in array context if the param
1229 # is not set
1230 foreach my $opt (@extra_options) {
1231 if (not exists $allowed_options{$opt}) {
1232 die_error(400, "Invalid option parameter");
1234 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1235 die_error(400, "Invalid option parameter for this action");
1239 our $hash_parent_base = $input_params{'hash_parent_base'};
1240 if (defined $hash_parent_base) {
1241 if (!is_valid_refname($hash_parent_base)) {
1242 die_error(400, "Invalid hash parent base parameter");
1246 # other parameters
1247 our $page = $input_params{'page'};
1248 if (defined $page) {
1249 if ($page =~ m/[^0-9]/) {
1250 die_error(400, "Invalid page parameter");
1254 our $searchtype = $input_params{'searchtype'};
1255 if (defined $searchtype) {
1256 if ($searchtype =~ m/[^a-z]/) {
1257 die_error(400, "Invalid searchtype parameter");
1261 our $search_use_regexp = $input_params{'search_use_regexp'};
1263 our $searchtext = $input_params{'searchtext'};
1264 our $search_regexp = undef;
1265 if (defined $searchtext) {
1266 if (length($searchtext) < 2) {
1267 die_error(403, "At least two characters are required for search parameter");
1269 if ($search_use_regexp) {
1270 $search_regexp = $searchtext;
1271 if (!eval { qr/$search_regexp/; 1; }) {
1272 (my $error = $@) =~ s/ at \S+ line \d+.*\n?//;
1273 die_error(400, "Invalid search regexp '$search_regexp'",
1274 esc_html($error));
1276 } else {
1277 $search_regexp = quotemeta $searchtext;
1282 # path to the current git repository
1283 our $git_dir;
1284 sub evaluate_git_dir {
1285 our $git_dir = "$projectroot/$project" if $project;
1288 our (@snapshot_fmts, $git_avatar, @extra_branch_refs);
1289 sub configure_gitweb_features {
1290 # list of supported snapshot formats
1291 our @snapshot_fmts = gitweb_get_feature('snapshot');
1292 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1294 # check that the avatar feature is set to a known provider name,
1295 # and for each provider check if the dependencies are satisfied.
1296 # if the provider name is invalid or the dependencies are not met,
1297 # reset $git_avatar to the empty string.
1298 our ($git_avatar) = gitweb_get_feature('avatar');
1299 if ($git_avatar eq 'gravatar') {
1300 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1301 } elsif ($git_avatar eq 'picon') {
1302 # no dependencies
1303 } else {
1304 $git_avatar = '';
1307 our @extra_branch_refs = gitweb_get_feature('extra-branch-refs');
1308 @extra_branch_refs = filter_and_validate_refs (@extra_branch_refs);
1311 sub get_branch_refs {
1312 return ('heads', @extra_branch_refs);
1315 # custom error handler: 'die <message>' is Internal Server Error
1316 sub handle_errors_html {
1317 my $msg = shift; # it is already HTML escaped
1319 # to avoid infinite loop where error occurs in die_error,
1320 # change handler to default handler, disabling handle_errors_html
1321 set_message("Error occurred when inside die_error:\n$msg");
1323 # you cannot jump out of die_error when called as error handler;
1324 # the subroutine set via CGI::Carp::set_message is called _after_
1325 # HTTP headers are already written, so it cannot write them itself
1326 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1328 set_message(\&handle_errors_html);
1330 # dispatch
1331 sub dispatch {
1332 if (!defined $action) {
1333 if (defined $hash) {
1334 $action = git_get_type($hash);
1335 $action or die_error(404, "Object does not exist");
1336 } elsif (defined $hash_base && defined $file_name) {
1337 $action = git_get_type("$hash_base:$file_name");
1338 $action or die_error(404, "File or directory does not exist");
1339 } elsif (defined $project) {
1340 $action = 'summary';
1341 } else {
1342 $action = 'project_list';
1345 if (!defined($actions{$action})) {
1346 die_error(400, "Unknown action");
1348 if ($action !~ m/^(?:opml|project_list|project_index)$/ &&
1349 !$project) {
1350 die_error(400, "Project needed");
1352 $actions{$action}->();
1355 sub reset_timer {
1356 our $t0 = [ gettimeofday() ]
1357 if defined $t0;
1358 our $number_of_git_cmds = 0;
1361 our $first_request = 1;
1362 our $evaluate_uri_force = undef;
1363 sub run_request {
1364 reset_timer();
1366 # Only allow GET and HEAD methods
1367 if (!$ENV{'REQUEST_METHOD'} || ($ENV{'REQUEST_METHOD'} ne 'GET' && $ENV{'REQUEST_METHOD'} ne 'HEAD')) {
1368 print <<EOT;
1369 Status: 405 Method Not Allowed
1370 Content-Type: text/plain
1371 Allow: GET,HEAD
1373 405 Method Not Allowed
1375 return;
1378 evaluate_uri();
1379 &$evaluate_uri_force() if $evaluate_uri_force;
1380 if ($per_request_config) {
1381 if (ref($per_request_config) eq 'CODE') {
1382 $per_request_config->();
1383 } elsif (!$first_request) {
1384 evaluate_gitweb_config();
1387 check_loadavg();
1389 # $projectroot and $projects_list might be set in gitweb config file
1390 $projects_list ||= $projectroot;
1392 evaluate_query_params();
1393 evaluate_path_info();
1394 evaluate_and_validate_params();
1395 evaluate_git_dir();
1397 configure_gitweb_features();
1399 dispatch();
1402 our $is_last_request = sub { 1 };
1403 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1404 our $CGI = 'CGI';
1405 our $cgi;
1406 our $fcgi_mode = 0;
1407 our $fcgi_nproc_active = 0;
1408 our $fcgi_raw_mode = 0;
1409 sub is_fcgi {
1410 use Errno;
1411 my $stdinfno = fileno STDIN;
1412 return 0 unless defined $stdinfno && $stdinfno == 0;
1413 return 0 unless getsockname STDIN;
1414 return 0 if getpeername STDIN;
1415 return $!{ENOTCONN}?1:0;
1417 sub configure_as_fcgi {
1418 return if $fcgi_mode;
1420 require FCGI;
1421 require CGI::Fast;
1423 # We have gone to great effort to make sure that all incoming data has
1424 # been converted from whatever format it was in into UTF-8. We have
1425 # even taken care to make sure the output handle is in ':utf8' mode.
1426 # Now along comes FCGI and blows it with:
1428 # Use of wide characters in FCGI::Stream::PRINT is deprecated
1429 # and will stop wprking[sic] in a future version of FCGI
1431 # To fix this we replace FCGI::Stream::PRINT with our own routine that
1432 # first encodes everything and then calls the original routine, but
1433 # not if $fcgi_raw_mode is true (then we just call the original routine).
1435 # Note that we could do this by using utf8::is_utf8 to check instead
1436 # of having a $fcgi_raw_mode global, but that would be slower to run
1437 # the test on each element and much slower than skipping the conversion
1438 # entirely when we know we're outputting raw bytes.
1439 my $orig = \&FCGI::Stream::PRINT;
1440 undef *FCGI::Stream::PRINT;
1441 *FCGI::Stream::PRINT = sub {
1442 @_ = (shift, map {my $x=$_; utf8::encode($x); $x} @_)
1443 unless $fcgi_raw_mode;
1444 goto $orig;
1447 our $CGI = 'CGI::Fast';
1449 $fcgi_mode = 1;
1450 $first_request = 0;
1451 my $request_number = 0;
1452 # let each child service 100 requests
1453 our $is_last_request = sub { ++$request_number > 100 };
1455 sub evaluate_argv {
1456 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1457 configure_as_fcgi()
1458 if $script_name =~ /\.fcgi$/ || ($auto_fcgi && is_fcgi());
1460 my $nproc_sub = sub {
1461 my ($arg, $val) = @_;
1462 return unless eval { require FCGI::ProcManager; 1; };
1463 $fcgi_nproc_active = 1;
1464 my $proc_manager = FCGI::ProcManager->new({
1465 n_processes => $val,
1467 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1468 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1469 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1471 if (@ARGV) {
1472 require Getopt::Long;
1473 Getopt::Long::GetOptions(
1474 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1475 'nproc|n=i' => $nproc_sub,
1478 if (!$fcgi_nproc_active && defined $ENV{'GITWEB_FCGI_NPROC'} && $ENV{'GITWEB_FCGI_NPROC'} =~ /^\d+$/) {
1479 &$nproc_sub('nproc', $ENV{'GITWEB_FCGI_NPROC'});
1483 sub run {
1484 evaluate_gitweb_config();
1485 evaluate_git_version();
1486 my ($mu, $hl, $subroutine) = ($my_uri, $home_link, '');
1487 $subroutine .= '$my_uri = $mu;' if defined $my_uri && $my_uri ne '';
1488 $subroutine .= '$home_link = $hl;' if defined $home_link && $home_link ne '';
1489 $evaluate_uri_force = eval "sub {$subroutine}" if $subroutine;
1490 $first_request = 1;
1491 evaluate_argv();
1493 $pre_listen_hook->()
1494 if $pre_listen_hook;
1496 REQUEST:
1497 while ($cgi = $CGI->new()) {
1498 $pre_dispatch_hook->()
1499 if $pre_dispatch_hook;
1501 run_request();
1503 $post_dispatch_hook->()
1504 if $post_dispatch_hook;
1505 $first_request = 0;
1507 last REQUEST if ($is_last_request->());
1510 DONE_GITWEB:
1514 run();
1516 if (defined caller) {
1517 # wrapped in a subroutine processing requests,
1518 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1519 return;
1520 } else {
1521 # pure CGI script, serving single request
1522 exit;
1525 ## ======================================================================
1526 ## action links
1528 # possible values of extra options
1529 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1530 # -replay => 1 - start from a current view (replay with modifications)
1531 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1532 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1533 sub href {
1534 my %params = @_;
1535 # default is to use -absolute url() i.e. $my_uri
1536 my $href = $params{-full} ? $my_url : $my_uri;
1538 # implicit -replay, must be first of implicit params
1539 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1541 $params{'project'} = $project unless exists $params{'project'};
1543 if ($params{-replay}) {
1544 while (my ($name, $symbol) = each %cgi_param_mapping) {
1545 if (!exists $params{$name}) {
1546 $params{$name} = $input_params{$name};
1551 my $use_pathinfo = gitweb_check_feature('pathinfo');
1552 if (defined $params{'project'} &&
1553 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1554 # try to put as many parameters as possible in PATH_INFO:
1555 # - project name
1556 # - action
1557 # - hash_parent or hash_parent_base:/file_parent
1558 # - hash or hash_base:/filename
1559 # - the snapshot_format as an appropriate suffix
1561 # When the script is the root DirectoryIndex for the domain,
1562 # $href here would be something like http://gitweb.example.com/
1563 # Thus, we strip any trailing / from $href, to spare us double
1564 # slashes in the final URL
1565 $href =~ s,/$,,;
1567 # Then add the project name, if present
1568 $href .= "/".esc_path_info($params{'project'});
1569 delete $params{'project'};
1571 # since we destructively absorb parameters, we keep this
1572 # boolean that remembers if we're handling a snapshot
1573 my $is_snapshot = $params{'action'} eq 'snapshot';
1575 # Summary just uses the project path URL, any other action is
1576 # added to the URL
1577 if (defined $params{'action'}) {
1578 $href .= "/".esc_path_info($params{'action'})
1579 unless $params{'action'} eq 'summary';
1580 delete $params{'action'};
1583 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1584 # stripping nonexistent or useless pieces
1585 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1586 || $params{'hash_parent'} || $params{'hash'});
1587 if (defined $params{'hash_base'}) {
1588 if (defined $params{'hash_parent_base'}) {
1589 $href .= esc_path_info($params{'hash_parent_base'});
1590 # skip the file_parent if it's the same as the file_name
1591 if (defined $params{'file_parent'}) {
1592 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1593 delete $params{'file_parent'};
1594 } elsif ($params{'file_parent'} !~ /\.\./) {
1595 $href .= ":/".esc_path_info($params{'file_parent'});
1596 delete $params{'file_parent'};
1599 $href .= "..";
1600 delete $params{'hash_parent'};
1601 delete $params{'hash_parent_base'};
1602 } elsif (defined $params{'hash_parent'}) {
1603 $href .= esc_path_info($params{'hash_parent'}). "..";
1604 delete $params{'hash_parent'};
1607 $href .= esc_path_info($params{'hash_base'});
1608 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1609 $href .= ":/".esc_path_info($params{'file_name'});
1610 delete $params{'file_name'};
1612 delete $params{'hash'};
1613 delete $params{'hash_base'};
1614 } elsif (defined $params{'hash'}) {
1615 $href .= esc_path_info($params{'hash'});
1616 delete $params{'hash'};
1619 # If the action was a snapshot, we can absorb the
1620 # snapshot_format parameter too
1621 if ($is_snapshot) {
1622 my $fmt = $params{'snapshot_format'};
1623 # snapshot_format should always be defined when href()
1624 # is called, but just in case some code forgets, we
1625 # fall back to the default
1626 $fmt ||= $snapshot_fmts[0];
1627 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1628 delete $params{'snapshot_format'};
1632 # now encode the parameters explicitly
1633 my @result = ();
1634 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1635 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1636 if (defined $params{$name}) {
1637 if (ref($params{$name}) eq "ARRAY") {
1638 foreach my $par (@{$params{$name}}) {
1639 push @result, $symbol . "=" . esc_param($par);
1641 } else {
1642 push @result, $symbol . "=" . esc_param($params{$name});
1646 $href .= "?" . join(';', @result) if scalar @result;
1648 # final transformation: trailing spaces must be escaped (URI-encoded)
1649 $href =~ s/(\s+)$/CGI::escape($1)/e;
1651 if ($params{-anchor}) {
1652 $href .= "#".esc_param($params{-anchor});
1655 return $href;
1659 ## ======================================================================
1660 ## validation, quoting/unquoting and escaping
1662 sub is_valid_action {
1663 my $input = shift;
1664 return undef unless exists $actions{$input};
1665 return 1;
1668 sub is_valid_project {
1669 my $input = shift;
1671 return unless defined $input;
1672 if (!is_valid_pathname($input) ||
1673 !(-d "$projectroot/$input") ||
1674 !check_export_ok("$projectroot/$input") ||
1675 ($strict_export && !project_in_list($input))) {
1676 return undef;
1677 } else {
1678 return 1;
1682 sub is_valid_pathname {
1683 my $input = shift;
1685 return undef unless defined $input;
1686 # no '.' or '..' as elements of path, i.e. no '.' or '..'
1687 # at the beginning, at the end, and between slashes.
1688 # also this catches doubled slashes
1689 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1690 return undef;
1692 # no null characters
1693 if ($input =~ m!\0!) {
1694 return undef;
1696 return 1;
1699 sub is_valid_ref_format {
1700 my $input = shift;
1702 return undef unless defined $input;
1703 # restrictions on ref name according to git-check-ref-format
1704 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1705 return undef;
1707 return 1;
1710 sub is_valid_refname {
1711 my $input = shift;
1713 return undef unless defined $input;
1714 # textual hashes are O.K.
1715 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1716 return 1;
1718 # it must be correct pathname
1719 is_valid_pathname($input) or return undef;
1720 # check git-check-ref-format restrictions
1721 is_valid_ref_format($input) or return undef;
1722 return 1;
1725 # decode sequences of octets in utf8 into Perl's internal form,
1726 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1727 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1728 sub to_utf8 {
1729 my $str = shift;
1730 return undef unless defined $str;
1732 if (utf8::is_utf8($str) || utf8::decode($str)) {
1733 return $str;
1734 } else {
1735 return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
1739 # quote unsafe chars, but keep the slash, even when it's not
1740 # correct, but quoted slashes look too horrible in bookmarks
1741 sub esc_param {
1742 my $str = shift;
1743 return undef unless defined $str;
1744 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1745 $str =~ s/ /\+/g;
1746 return $str;
1749 # the quoting rules for path_info fragment are slightly different
1750 sub esc_path_info {
1751 my $str = shift;
1752 return undef unless defined $str;
1754 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1755 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1757 return $str;
1760 # quote unsafe chars in whole URL, so some characters cannot be quoted
1761 sub esc_url {
1762 my $str = shift;
1763 return undef unless defined $str;
1764 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1765 $str =~ s/ /\+/g;
1766 return $str;
1769 # quote unsafe characters in HTML attributes
1770 sub esc_attr {
1772 # for XHTML conformance escaping '"' to '&quot;' is not enough
1773 return esc_html(@_);
1776 # replace invalid utf8 character with SUBSTITUTION sequence
1777 sub esc_html {
1778 my $str = shift;
1779 my %opts = @_;
1781 return undef unless defined $str;
1783 $str = to_utf8($str);
1784 $str = $cgi->escapeHTML($str);
1785 if ($opts{'-nbsp'}) {
1786 $str =~ s/ /&nbsp;/g;
1788 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1789 return $str;
1792 # quote control characters and escape filename to HTML
1793 sub esc_path {
1794 my $str = shift;
1795 my %opts = @_;
1797 return undef unless defined $str;
1799 $str = to_utf8($str);
1800 $str = $cgi->escapeHTML($str);
1801 if ($opts{'-nbsp'}) {
1802 $str =~ s/ /&nbsp;/g;
1804 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1805 return $str;
1808 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1809 sub sanitize {
1810 my $str = shift;
1812 return undef unless defined $str;
1814 $str = to_utf8($str);
1815 $str =~ s|([[:cntrl:]])|(index("\t\n\r", $1) != -1 ? $1 : quot_cec($1))|eg;
1816 return $str;
1819 # Make control characters "printable", using character escape codes (CEC)
1820 sub quot_cec {
1821 my $cntrl = shift;
1822 my %opts = @_;
1823 my %es = ( # character escape codes, aka escape sequences
1824 "\t" => '\t', # tab (HT)
1825 "\n" => '\n', # line feed (LF)
1826 "\r" => '\r', # carrige return (CR)
1827 "\f" => '\f', # form feed (FF)
1828 "\b" => '\b', # backspace (BS)
1829 "\a" => '\a', # alarm (bell) (BEL)
1830 "\e" => '\e', # escape (ESC)
1831 "\013" => '\v', # vertical tab (VT)
1832 "\000" => '\0', # nul character (NUL)
1834 my $chr = ( (exists $es{$cntrl})
1835 ? $es{$cntrl}
1836 : sprintf('\%2x', ord($cntrl)) );
1837 if ($opts{-nohtml}) {
1838 return $chr;
1839 } else {
1840 return "<span class=\"cntrl\">$chr</span>";
1844 # Alternatively use unicode control pictures codepoints,
1845 # Unicode "printable representation" (PR)
1846 sub quot_upr {
1847 my $cntrl = shift;
1848 my %opts = @_;
1850 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
1851 if ($opts{-nohtml}) {
1852 return $chr;
1853 } else {
1854 return "<span class=\"cntrl\">$chr</span>";
1858 # git may return quoted and escaped filenames
1859 sub unquote {
1860 my $str = shift;
1862 sub unq {
1863 my $seq = shift;
1864 my %es = ( # character escape codes, aka escape sequences
1865 't' => "\t", # tab (HT, TAB)
1866 'n' => "\n", # newline (NL)
1867 'r' => "\r", # return (CR)
1868 'f' => "\f", # form feed (FF)
1869 'b' => "\b", # backspace (BS)
1870 'a' => "\a", # alarm (bell) (BEL)
1871 'e' => "\e", # escape (ESC)
1872 'v' => "\013", # vertical tab (VT)
1875 if ($seq =~ m/^[0-7]{1,3}$/) {
1876 # octal char sequence
1877 return chr(oct($seq));
1878 } elsif (exists $es{$seq}) {
1879 # C escape sequence, aka character escape code
1880 return $es{$seq};
1882 # quoted ordinary character
1883 return $seq;
1886 if ($str =~ m/^"(.*)"$/) {
1887 # needs unquoting
1888 $str = $1;
1889 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
1891 return $str;
1894 # escape tabs (convert tabs to spaces)
1895 sub untabify {
1896 my $line = shift;
1898 while ((my $pos = index($line, "\t")) != -1) {
1899 if (my $count = (8 - ($pos % 8))) {
1900 my $spaces = ' ' x $count;
1901 $line =~ s/\t/$spaces/;
1905 return $line;
1908 sub project_in_list {
1909 my $project = shift;
1910 my @list = git_get_projects_list();
1911 return @list && scalar(grep { $_->{'path'} eq $project } @list);
1914 ## ----------------------------------------------------------------------
1915 ## HTML aware string manipulation
1917 # Try to chop given string on a word boundary between position
1918 # $len and $len+$add_len. If there is no word boundary there,
1919 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
1920 # (marking chopped part) would be longer than given string.
1921 sub chop_str {
1922 my $str = shift;
1923 my $len = shift;
1924 my $add_len = shift || 10;
1925 my $where = shift || 'right'; # 'left' | 'center' | 'right'
1927 # Make sure perl knows it is utf8 encoded so we don't
1928 # cut in the middle of a utf8 multibyte char.
1929 $str = to_utf8($str);
1931 # allow only $len chars, but don't cut a word if it would fit in $add_len
1932 # if it doesn't fit, cut it if it's still longer than the dots we would add
1933 # remove chopped character entities entirely
1935 # when chopping in the middle, distribute $len into left and right part
1936 # return early if chopping wouldn't make string shorter
1937 if ($where eq 'center') {
1938 return $str if ($len + 5 >= length($str)); # filler is length 5
1939 $len = int($len/2);
1940 } else {
1941 return $str if ($len + 4 >= length($str)); # filler is length 4
1944 # regexps: ending and beginning with word part up to $add_len
1945 my $endre = qr/.{$len}\w{0,$add_len}/;
1946 my $begre = qr/\w{0,$add_len}.{$len}/;
1948 if ($where eq 'left') {
1949 $str =~ m/^(.*?)($begre)$/;
1950 my ($lead, $body) = ($1, $2);
1951 if (length($lead) > 4) {
1952 $lead = " ...";
1954 return "$lead$body";
1956 } elsif ($where eq 'center') {
1957 $str =~ m/^($endre)(.*)$/;
1958 my ($left, $str) = ($1, $2);
1959 $str =~ m/^(.*?)($begre)$/;
1960 my ($mid, $right) = ($1, $2);
1961 if (length($mid) > 5) {
1962 $mid = " ... ";
1964 return "$left$mid$right";
1966 } else {
1967 $str =~ m/^($endre)(.*)$/;
1968 my $body = $1;
1969 my $tail = $2;
1970 if (length($tail) > 4) {
1971 $tail = "... ";
1973 return "$body$tail";
1977 # takes the same arguments as chop_str, but also wraps a <span> around the
1978 # result with a title attribute if it does get chopped. Additionally, the
1979 # string is HTML-escaped.
1980 sub chop_and_escape_str {
1981 my ($str) = @_;
1983 my $chopped = chop_str(@_);
1984 $str = to_utf8($str);
1985 if ($chopped eq $str) {
1986 return esc_html($chopped);
1987 } else {
1988 $str =~ s/[[:cntrl:]]/?/g;
1989 return $cgi->span({-title=>$str}, esc_html($chopped));
1993 # Highlight selected fragments of string, using given CSS class,
1994 # and escape HTML. It is assumed that fragments do not overlap.
1995 # Regions are passed as list of pairs (array references).
1997 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
1998 # '<span class="mark">foo</span>bar'
1999 sub esc_html_hl_regions {
2000 my ($str, $css_class, @sel) = @_;
2001 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
2002 @sel = grep { ref($_) eq 'ARRAY' } @sel;
2003 return esc_html($str, %opts) unless @sel;
2005 my $out = '';
2006 my $pos = 0;
2008 for my $s (@sel) {
2009 my ($begin, $end) = @$s;
2011 # Don't create empty <span> elements.
2012 next if $end <= $begin;
2014 my $escaped = esc_html(substr($str, $begin, $end - $begin),
2015 %opts);
2017 $out .= esc_html(substr($str, $pos, $begin - $pos), %opts)
2018 if ($begin - $pos > 0);
2019 $out .= $cgi->span({-class => $css_class}, $escaped);
2021 $pos = $end;
2023 $out .= esc_html(substr($str, $pos), %opts)
2024 if ($pos < length($str));
2026 return $out;
2029 # return positions of beginning and end of each match
2030 sub matchpos_list {
2031 my ($str, $regexp) = @_;
2032 return unless (defined $str && defined $regexp);
2034 my @matches;
2035 while ($str =~ /$regexp/g) {
2036 push @matches, [$-[0], $+[0]];
2038 return @matches;
2041 # highlight match (if any), and escape HTML
2042 sub esc_html_match_hl {
2043 my ($str, $regexp) = @_;
2044 return esc_html($str) unless defined $regexp;
2046 my @matches = matchpos_list($str, $regexp);
2047 return esc_html($str) unless @matches;
2049 return esc_html_hl_regions($str, 'match', @matches);
2053 # highlight match (if any) of shortened string, and escape HTML
2054 sub esc_html_match_hl_chopped {
2055 my ($str, $chopped, $regexp) = @_;
2056 return esc_html_match_hl($str, $regexp) unless defined $chopped;
2058 my @matches = matchpos_list($str, $regexp);
2059 return esc_html($chopped) unless @matches;
2061 # filter matches so that we mark chopped string
2062 my $tail = "... "; # see chop_str
2063 unless ($chopped =~ s/\Q$tail\E$//) {
2064 $tail = '';
2066 my $chop_len = length($chopped);
2067 my $tail_len = length($tail);
2068 my @filtered;
2070 for my $m (@matches) {
2071 if ($m->[0] > $chop_len) {
2072 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
2073 last;
2074 } elsif ($m->[1] > $chop_len) {
2075 push @filtered, [ $m->[0], $chop_len + $tail_len ];
2076 last;
2078 push @filtered, $m;
2081 return esc_html_hl_regions($chopped . $tail, 'match', @filtered);
2084 ## ----------------------------------------------------------------------
2085 ## functions returning short strings
2087 # CSS class for given age value (in seconds)
2088 sub age_class {
2089 my $age = shift;
2091 if (!defined $age) {
2092 return "noage";
2093 } elsif ($age < 60*60*2) {
2094 return "age0";
2095 } elsif ($age < 60*60*24*2) {
2096 return "age1";
2097 } else {
2098 return "age2";
2102 # convert age in seconds to "nn units ago" string
2103 sub age_string {
2104 my $age = shift;
2105 my $age_str;
2107 if ($age > 60*60*24*365*2) {
2108 $age_str = (int $age/60/60/24/365);
2109 $age_str .= " years ago";
2110 } elsif ($age > 60*60*24*(365/12)*2) {
2111 $age_str = int $age/60/60/24/(365/12);
2112 $age_str .= " months ago";
2113 } elsif ($age > 60*60*24*7*2) {
2114 $age_str = int $age/60/60/24/7;
2115 $age_str .= " weeks ago";
2116 } elsif ($age > 60*60*24*2) {
2117 $age_str = int $age/60/60/24;
2118 $age_str .= " days ago";
2119 } elsif ($age > 60*60*2) {
2120 $age_str = int $age/60/60;
2121 $age_str .= " hours ago";
2122 } elsif ($age > 60*2) {
2123 $age_str = int $age/60;
2124 $age_str .= " min ago";
2125 } elsif ($age > 2) {
2126 $age_str = int $age;
2127 $age_str .= " sec ago";
2128 } else {
2129 $age_str .= " right now";
2131 return $age_str;
2134 use constant {
2135 S_IFINVALID => 0030000,
2136 S_IFGITLINK => 0160000,
2139 # submodule/subproject, a commit object reference
2140 sub S_ISGITLINK {
2141 my $mode = shift;
2143 return (($mode & S_IFMT) == S_IFGITLINK)
2146 # convert file mode in octal to symbolic file mode string
2147 sub mode_str {
2148 my $mode = oct shift;
2150 if (S_ISGITLINK($mode)) {
2151 return 'm---------';
2152 } elsif (S_ISDIR($mode & S_IFMT)) {
2153 return 'drwxr-xr-x';
2154 } elsif (S_ISLNK($mode)) {
2155 return 'lrwxrwxrwx';
2156 } elsif (S_ISREG($mode)) {
2157 # git cares only about the executable bit
2158 if ($mode & S_IXUSR) {
2159 return '-rwxr-xr-x';
2160 } else {
2161 return '-rw-r--r--';
2163 } else {
2164 return '----------';
2168 # convert file mode in octal to file type string
2169 sub file_type {
2170 my $mode = shift;
2172 if ($mode !~ m/^[0-7]+$/) {
2173 return $mode;
2174 } else {
2175 $mode = oct $mode;
2178 if (S_ISGITLINK($mode)) {
2179 return "submodule";
2180 } elsif (S_ISDIR($mode & S_IFMT)) {
2181 return "directory";
2182 } elsif (S_ISLNK($mode)) {
2183 return "symlink";
2184 } elsif (S_ISREG($mode)) {
2185 return "file";
2186 } else {
2187 return "unknown";
2191 # convert file mode in octal to file type description string
2192 sub file_type_long {
2193 my $mode = shift;
2195 if ($mode !~ m/^[0-7]+$/) {
2196 return $mode;
2197 } else {
2198 $mode = oct $mode;
2201 if (S_ISGITLINK($mode)) {
2202 return "submodule";
2203 } elsif (S_ISDIR($mode & S_IFMT)) {
2204 return "directory";
2205 } elsif (S_ISLNK($mode)) {
2206 return "symlink";
2207 } elsif (S_ISREG($mode)) {
2208 if ($mode & S_IXUSR) {
2209 return "executable";
2210 } else {
2211 return "file";
2213 } else {
2214 return "unknown";
2219 ## ----------------------------------------------------------------------
2220 ## functions returning short HTML fragments, or transforming HTML fragments
2221 ## which don't belong to other sections
2223 # format line of commit message.
2224 sub format_log_line_html {
2225 my $line = shift;
2227 $line = esc_html($line, -nbsp=>1);
2228 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
2229 $cgi->a({-href => href(action=>"object", hash=>$1),
2230 -class => "text"}, $1);
2231 }eg;
2233 return $line;
2236 # format marker of refs pointing to given object
2238 # the destination action is chosen based on object type and current context:
2239 # - for annotated tags, we choose the tag view unless it's the current view
2240 # already, in which case we go to shortlog view
2241 # - for other refs, we keep the current view if we're in history, shortlog or
2242 # log view, and select shortlog otherwise
2243 sub format_ref_marker {
2244 my ($refs, $id) = @_;
2245 my $markers = '';
2247 if (defined $refs->{$id}) {
2248 foreach my $ref (@{$refs->{$id}}) {
2249 # this code exploits the fact that non-lightweight tags are the
2250 # only indirect objects, and that they are the only objects for which
2251 # we want to use tag instead of shortlog as action
2252 my ($type, $name) = qw();
2253 my $indirect = ($ref =~ s/\^\{\}$//);
2254 # e.g. tags/v2.6.11 or heads/next
2255 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2256 $type = $1;
2257 $name = $2;
2258 } else {
2259 $type = "ref";
2260 $name = $ref;
2263 my $class = $type;
2264 $class .= " indirect" if $indirect;
2266 my $dest_action = "shortlog";
2268 if ($indirect) {
2269 $dest_action = "tag" unless $action eq "tag";
2270 } elsif ($action =~ /^(history|(short)?log)$/) {
2271 $dest_action = $action;
2274 my $dest = "";
2275 $dest .= "refs/" unless $ref =~ m!^refs/!;
2276 $dest .= $ref;
2278 my $link = $cgi->a({
2279 -href => href(
2280 action=>$dest_action,
2281 hash=>$dest
2282 )}, $name);
2284 $markers .= " <span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
2285 $link . "</span>";
2289 if ($markers) {
2290 return ' <span class="refs">'. $markers . '</span>';
2291 } else {
2292 return "";
2296 # format, perhaps shortened and with markers, title line
2297 sub format_subject_html {
2298 my ($long, $short, $href, $extra) = @_;
2299 $extra = '' unless defined($extra);
2301 if (length($short) < length($long)) {
2302 $long =~ s/[[:cntrl:]]/?/g;
2303 return $cgi->a({-href => $href, -class => "list subject",
2304 -title => to_utf8($long)},
2305 esc_html($short)) . $extra;
2306 } else {
2307 return $cgi->a({-href => $href, -class => "list subject"},
2308 esc_html($long)) . $extra;
2312 # Rather than recomputing the url for an email multiple times, we cache it
2313 # after the first hit. This gives a visible benefit in views where the avatar
2314 # for the same email is used repeatedly (e.g. shortlog).
2315 # The cache is shared by all avatar engines (currently gravatar only), which
2316 # are free to use it as preferred. Since only one avatar engine is used for any
2317 # given page, there's no risk for cache conflicts.
2318 our %avatar_cache = ();
2320 # Compute the picon url for a given email, by using the picon search service over at
2321 # http://www.cs.indiana.edu/picons/search.html
2322 sub picon_url {
2323 my $email = lc shift;
2324 if (!$avatar_cache{$email}) {
2325 my ($user, $domain) = split('@', $email);
2326 $avatar_cache{$email} =
2327 "//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2328 "$domain/$user/" .
2329 "users+domains+unknown/up/single";
2331 return $avatar_cache{$email};
2334 # Compute the gravatar url for a given email, if it's not in the cache already.
2335 # Gravatar stores only the part of the URL before the size, since that's the
2336 # one computationally more expensive. This also allows reuse of the cache for
2337 # different sizes (for this particular engine).
2338 sub gravatar_url {
2339 my $email = lc shift;
2340 my $size = shift;
2341 $avatar_cache{$email} ||=
2342 "//www.gravatar.com/avatar/" .
2343 Digest::MD5::md5_hex($email) . "?s=";
2344 return $avatar_cache{$email} . $size;
2347 # Insert an avatar for the given $email at the given $size if the feature
2348 # is enabled.
2349 sub git_get_avatar {
2350 my ($email, %opts) = @_;
2351 my $pre_white = ($opts{-pad_before} ? "&nbsp;" : "");
2352 my $post_white = ($opts{-pad_after} ? "&nbsp;" : "");
2353 $opts{-size} ||= 'default';
2354 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2355 my $url = "";
2356 if ($git_avatar eq 'gravatar') {
2357 $url = gravatar_url($email, $size);
2358 } elsif ($git_avatar eq 'picon') {
2359 $url = picon_url($email);
2361 # Other providers can be added by extending the if chain, defining $url
2362 # as needed. If no variant puts something in $url, we assume avatars
2363 # are completely disabled/unavailable.
2364 if ($url) {
2365 return $pre_white .
2366 "<img width=\"$size\" " .
2367 "class=\"avatar\" " .
2368 "src=\"".esc_url($url)."\" " .
2369 "alt=\"\" " .
2370 "/>" . $post_white;
2371 } else {
2372 return "";
2376 sub format_search_author {
2377 my ($author, $searchtype, $displaytext) = @_;
2378 my $have_search = gitweb_check_feature('search');
2380 if ($have_search) {
2381 my $performed = "";
2382 if ($searchtype eq 'author') {
2383 $performed = "authored";
2384 } elsif ($searchtype eq 'committer') {
2385 $performed = "committed";
2388 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2389 searchtext=>$author,
2390 searchtype=>$searchtype), class=>"list",
2391 title=>"Search for commits $performed by $author"},
2392 $displaytext);
2394 } else {
2395 return $displaytext;
2399 # format the author name of the given commit with the given tag
2400 # the author name is chopped and escaped according to the other
2401 # optional parameters (see chop_str).
2402 sub format_author_html {
2403 my $tag = shift;
2404 my $co = shift;
2405 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2406 return "<$tag class=\"author\">" .
2407 format_search_author($co->{'author_name'}, "author",
2408 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2409 $author) .
2410 "</$tag>";
2413 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2414 sub format_git_diff_header_line {
2415 my $line = shift;
2416 my $diffinfo = shift;
2417 my ($from, $to) = @_;
2419 if ($diffinfo->{'nparents'}) {
2420 # combined diff
2421 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2422 if ($to->{'href'}) {
2423 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2424 esc_path($to->{'file'}));
2425 } else { # file was deleted (no href)
2426 $line .= esc_path($to->{'file'});
2428 } else {
2429 # "ordinary" diff
2430 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2431 if ($from->{'href'}) {
2432 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2433 'a/' . esc_path($from->{'file'}));
2434 } else { # file was added (no href)
2435 $line .= 'a/' . esc_path($from->{'file'});
2437 $line .= ' ';
2438 if ($to->{'href'}) {
2439 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2440 'b/' . esc_path($to->{'file'}));
2441 } else { # file was deleted
2442 $line .= 'b/' . esc_path($to->{'file'});
2446 return "<div class=\"diff header\">$line</div>\n";
2449 # format extended diff header line, before patch itself
2450 sub format_extended_diff_header_line {
2451 my $line = shift;
2452 my $diffinfo = shift;
2453 my ($from, $to) = @_;
2455 # match <path>
2456 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2457 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2458 esc_path($from->{'file'}));
2460 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2461 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2462 esc_path($to->{'file'}));
2464 # match single <mode>
2465 if ($line =~ m/\s(\d{6})$/) {
2466 $line .= '<span class="info"> (' .
2467 file_type_long($1) .
2468 ')</span>';
2470 # match <hash>
2471 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2472 # can match only for combined diff
2473 $line = 'index ';
2474 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2475 if ($from->{'href'}[$i]) {
2476 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2477 -class=>"hash"},
2478 substr($diffinfo->{'from_id'}[$i],0,7));
2479 } else {
2480 $line .= '0' x 7;
2482 # separator
2483 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2485 $line .= '..';
2486 if ($to->{'href'}) {
2487 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2488 substr($diffinfo->{'to_id'},0,7));
2489 } else {
2490 $line .= '0' x 7;
2493 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2494 # can match only for ordinary diff
2495 my ($from_link, $to_link);
2496 if ($from->{'href'}) {
2497 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2498 substr($diffinfo->{'from_id'},0,7));
2499 } else {
2500 $from_link = '0' x 7;
2502 if ($to->{'href'}) {
2503 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2504 substr($diffinfo->{'to_id'},0,7));
2505 } else {
2506 $to_link = '0' x 7;
2508 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2509 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2512 return $line . "<br/>\n";
2515 # format from-file/to-file diff header
2516 sub format_diff_from_to_header {
2517 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2518 my $line;
2519 my $result = '';
2521 $line = $from_line;
2522 #assert($line =~ m/^---/) if DEBUG;
2523 # no extra formatting for "^--- /dev/null"
2524 if (! $diffinfo->{'nparents'}) {
2525 # ordinary (single parent) diff
2526 if ($line =~ m!^--- "?a/!) {
2527 if ($from->{'href'}) {
2528 $line = '--- a/' .
2529 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2530 esc_path($from->{'file'}));
2531 } else {
2532 $line = '--- a/' .
2533 esc_path($from->{'file'});
2536 $result .= qq!<div class="diff from_file">$line</div>\n!;
2538 } else {
2539 # combined diff (merge commit)
2540 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2541 if ($from->{'href'}[$i]) {
2542 $line = '--- ' .
2543 $cgi->a({-href=>href(action=>"blobdiff",
2544 hash_parent=>$diffinfo->{'from_id'}[$i],
2545 hash_parent_base=>$parents[$i],
2546 file_parent=>$from->{'file'}[$i],
2547 hash=>$diffinfo->{'to_id'},
2548 hash_base=>$hash,
2549 file_name=>$to->{'file'}),
2550 -class=>"path",
2551 -title=>"diff" . ($i+1)},
2552 $i+1) .
2553 '/' .
2554 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
2555 esc_path($from->{'file'}[$i]));
2556 } else {
2557 $line = '--- /dev/null';
2559 $result .= qq!<div class="diff from_file">$line</div>\n!;
2563 $line = $to_line;
2564 #assert($line =~ m/^\+\+\+/) if DEBUG;
2565 # no extra formatting for "^+++ /dev/null"
2566 if ($line =~ m!^\+\+\+ "?b/!) {
2567 if ($to->{'href'}) {
2568 $line = '+++ b/' .
2569 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2570 esc_path($to->{'file'}));
2571 } else {
2572 $line = '+++ b/' .
2573 esc_path($to->{'file'});
2576 $result .= qq!<div class="diff to_file">$line</div>\n!;
2578 return $result;
2581 # create note for patch simplified by combined diff
2582 sub format_diff_cc_simplified {
2583 my ($diffinfo, @parents) = @_;
2584 my $result = '';
2586 $result .= "<div class=\"diff header\">" .
2587 "diff --cc ";
2588 if (!is_deleted($diffinfo)) {
2589 $result .= $cgi->a({-href => href(action=>"blob",
2590 hash_base=>$hash,
2591 hash=>$diffinfo->{'to_id'},
2592 file_name=>$diffinfo->{'to_file'}),
2593 -class => "path"},
2594 esc_path($diffinfo->{'to_file'}));
2595 } else {
2596 $result .= esc_path($diffinfo->{'to_file'});
2598 $result .= "</div>\n" . # class="diff header"
2599 "<div class=\"diff nodifferences\">" .
2600 "Simple merge" .
2601 "</div>\n"; # class="diff nodifferences"
2603 return $result;
2606 sub diff_line_class {
2607 my ($line, $from, $to) = @_;
2609 # ordinary diff
2610 my $num_sign = 1;
2611 # combined diff
2612 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
2613 $num_sign = scalar @{$from->{'href'}};
2616 my @diff_line_classifier = (
2617 { regexp => qr/^\@\@{$num_sign} /, class => "chunk_header"},
2618 { regexp => qr/^\\/, class => "incomplete" },
2619 { regexp => qr/^ {$num_sign}/, class => "ctx" },
2620 # classifier for context must come before classifier add/rem,
2621 # or we would have to use more complicated regexp, for example
2622 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
2623 { regexp => qr/^[+ ]{$num_sign}/, class => "add" },
2624 { regexp => qr/^[- ]{$num_sign}/, class => "rem" },
2626 for my $clsfy (@diff_line_classifier) {
2627 return $clsfy->{'class'}
2628 if ($line =~ $clsfy->{'regexp'});
2631 # fallback
2632 return "";
2635 # assumes that $from and $to are defined and correctly filled,
2636 # and that $line holds a line of chunk header for unified diff
2637 sub format_unidiff_chunk_header {
2638 my ($line, $from, $to) = @_;
2640 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
2641 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
2643 $from_lines = 0 unless defined $from_lines;
2644 $to_lines = 0 unless defined $to_lines;
2646 if ($from->{'href'}) {
2647 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
2648 -class=>"list"}, $from_text);
2650 if ($to->{'href'}) {
2651 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
2652 -class=>"list"}, $to_text);
2654 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
2655 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2656 return $line;
2659 # assumes that $from and $to are defined and correctly filled,
2660 # and that $line holds a line of chunk header for combined diff
2661 sub format_cc_diff_chunk_header {
2662 my ($line, $from, $to) = @_;
2664 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
2665 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
2667 @from_text = split(' ', $ranges);
2668 for (my $i = 0; $i < @from_text; ++$i) {
2669 ($from_start[$i], $from_nlines[$i]) =
2670 (split(',', substr($from_text[$i], 1)), 0);
2673 $to_text = pop @from_text;
2674 $to_start = pop @from_start;
2675 $to_nlines = pop @from_nlines;
2677 $line = "<span class=\"chunk_info\">$prefix ";
2678 for (my $i = 0; $i < @from_text; ++$i) {
2679 if ($from->{'href'}[$i]) {
2680 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
2681 -class=>"list"}, $from_text[$i]);
2682 } else {
2683 $line .= $from_text[$i];
2685 $line .= " ";
2687 if ($to->{'href'}) {
2688 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
2689 -class=>"list"}, $to_text);
2690 } else {
2691 $line .= $to_text;
2693 $line .= " $prefix</span>" .
2694 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
2695 return $line;
2698 # process patch (diff) line (not to be used for diff headers),
2699 # returning HTML-formatted (but not wrapped) line.
2700 # If the line is passed as a reference, it is treated as HTML and not
2701 # esc_html()'ed.
2702 sub format_diff_line {
2703 my ($line, $diff_class, $from, $to) = @_;
2705 if (ref($line)) {
2706 $line = $$line;
2707 } else {
2708 chomp $line;
2709 $line = untabify($line);
2711 if ($from && $to && $line =~ m/^\@{2} /) {
2712 $line = format_unidiff_chunk_header($line, $from, $to);
2713 } elsif ($from && $to && $line =~ m/^\@{3}/) {
2714 $line = format_cc_diff_chunk_header($line, $from, $to);
2715 } else {
2716 $line = esc_html($line, -nbsp=>1);
2720 my $diff_classes = "diff";
2721 $diff_classes .= " $diff_class" if ($diff_class);
2722 $line = "<div class=\"$diff_classes\">$line</div>\n";
2724 return $line;
2727 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
2728 # linked. Pass the hash of the tree/commit to snapshot.
2729 sub format_snapshot_links {
2730 my ($hash) = @_;
2731 my $num_fmts = @snapshot_fmts;
2732 if ($num_fmts > 1) {
2733 # A parenthesized list of links bearing format names.
2734 # e.g. "snapshot (_tar.gz_ _zip_)"
2735 return "snapshot (" . join(' ', map
2736 $cgi->a({
2737 -href => href(
2738 action=>"snapshot",
2739 hash=>$hash,
2740 snapshot_format=>$_
2742 }, $known_snapshot_formats{$_}{'display'})
2743 , @snapshot_fmts) . ")";
2744 } elsif ($num_fmts == 1) {
2745 # A single "snapshot" link whose tooltip bears the format name.
2746 # i.e. "_snapshot_"
2747 my ($fmt) = @snapshot_fmts;
2748 return
2749 $cgi->a({
2750 -href => href(
2751 action=>"snapshot",
2752 hash=>$hash,
2753 snapshot_format=>$fmt
2755 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
2756 }, "snapshot");
2757 } else { # $num_fmts == 0
2758 return undef;
2762 ## ......................................................................
2763 ## functions returning values to be passed, perhaps after some
2764 ## transformation, to other functions; e.g. returning arguments to href()
2766 # returns hash to be passed to href to generate gitweb URL
2767 # in -title key it returns description of link
2768 sub get_feed_info {
2769 my $format = shift || 'Atom';
2770 my %res = (action => lc($format));
2771 my $matched_ref = 0;
2773 # feed links are possible only for project views
2774 return unless (defined $project);
2775 # some views should link to OPML, or to generic project feed,
2776 # or don't have specific feed yet (so they should use generic)
2777 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
2779 my $branch = undef;
2780 # branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix
2781 # (fullname) to differentiate from tag links; this also makes
2782 # possible to detect branch links
2783 for my $ref (get_branch_refs()) {
2784 if ((defined $hash_base && $hash_base =~ m!^refs/\Q$ref\E/(.*)$!) ||
2785 (defined $hash && $hash =~ m!^refs/\Q$ref\E/(.*)$!)) {
2786 $branch = $1;
2787 $matched_ref = $ref;
2788 last;
2791 # find log type for feed description (title)
2792 my $type = 'log';
2793 if (defined $file_name) {
2794 $type = "history of $file_name";
2795 $type .= "/" if ($action eq 'tree');
2796 $type .= " on '$branch'" if (defined $branch);
2797 } else {
2798 $type = "log of $branch" if (defined $branch);
2801 $res{-title} = $type;
2802 $res{'hash'} = (defined $branch ? "refs/$matched_ref/$branch" : undef);
2803 $res{'file_name'} = $file_name;
2805 return %res;
2808 ## ----------------------------------------------------------------------
2809 ## git utility subroutines, invoking git commands
2811 # returns path to the core git executable and the --git-dir parameter as list
2812 sub git_cmd {
2813 $number_of_git_cmds++;
2814 return $GIT, '--git-dir='.$git_dir;
2817 # opens a "-|" cmd pipe handle with 2>/dev/null and returns it
2818 sub cmd_pipe {
2820 # In order to be compatible with FCGI mode we must use POSIX
2821 # and access the STDERR_FILENO file descriptor directly
2823 use POSIX qw(STDERR_FILENO dup dup2);
2825 open(my $null, '>', File::Spec->devnull) or die "couldn't open devnull: $!";
2826 (my $saveerr = dup(STDERR_FILENO)) or die "couldn't dup STDERR: $!";
2827 my $dup2ok = dup2(fileno($null), STDERR_FILENO);
2828 close($null) or !$dup2ok or die "couldn't close NULL: $!";
2829 $dup2ok or POSIX::close($saveerr), die "couldn't dup NULL to STDERR: $!";
2830 my $result = open(my $fd, "-|", @_);
2831 $dup2ok = dup2($saveerr, STDERR_FILENO);
2832 POSIX::close($saveerr) or !$dup2ok or die "couldn't close SAVEERR: $!";
2833 $dup2ok or die "couldn't dup SAVERR to STDERR: $!";
2835 return $result ? $fd : undef;
2838 # opens a "-|" git_cmd pipe handle with 2>/dev/null and returns it
2839 sub git_cmd_pipe {
2840 return cmd_pipe git_cmd(), @_;
2843 # quote the given arguments for passing them to the shell
2844 # quote_command("command", "arg 1", "arg with ' and ! characters")
2845 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
2846 # Try to avoid using this function wherever possible.
2847 sub quote_command {
2848 return join(' ',
2849 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
2852 # get HEAD ref of given project as hash
2853 sub git_get_head_hash {
2854 return git_get_full_hash(shift, 'HEAD');
2857 sub git_get_full_hash {
2858 return git_get_hash(@_);
2861 sub git_get_short_hash {
2862 return git_get_hash(@_, '--short=7');
2865 sub git_get_hash {
2866 my ($project, $hash, @options) = @_;
2867 my $o_git_dir = $git_dir;
2868 my $retval = undef;
2869 $git_dir = "$projectroot/$project";
2870 if (defined(my $fd = git_cmd_pipe 'rev-parse',
2871 '--verify', '-q', @options, $hash)) {
2872 $retval = <$fd>;
2873 chomp $retval if defined $retval;
2874 close $fd;
2876 if (defined $o_git_dir) {
2877 $git_dir = $o_git_dir;
2879 return $retval;
2882 # get type of given object
2883 sub git_get_type {
2884 my $hash = shift;
2886 defined(my $fd = git_cmd_pipe "cat-file", '-t', $hash) or return;
2887 my $type = <$fd>;
2888 close $fd or return;
2889 chomp $type;
2890 return $type;
2893 # repository configuration
2894 our $config_file = '';
2895 our %config;
2897 # store multiple values for single key as anonymous array reference
2898 # single values stored directly in the hash, not as [ <value> ]
2899 sub hash_set_multi {
2900 my ($hash, $key, $value) = @_;
2902 if (!exists $hash->{$key}) {
2903 $hash->{$key} = $value;
2904 } elsif (!ref $hash->{$key}) {
2905 $hash->{$key} = [ $hash->{$key}, $value ];
2906 } else {
2907 push @{$hash->{$key}}, $value;
2911 # return hash of git project configuration
2912 # optionally limited to some section, e.g. 'gitweb'
2913 sub git_parse_project_config {
2914 my $section_regexp = shift;
2915 my %config;
2917 local $/ = "\0";
2919 defined(my $fh = git_cmd_pipe "config", '-z', '-l')
2920 or return;
2922 while (my $keyval = to_utf8(scalar <$fh>)) {
2923 chomp $keyval;
2924 my ($key, $value) = split(/\n/, $keyval, 2);
2926 hash_set_multi(\%config, $key, $value)
2927 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
2929 close $fh;
2931 return %config;
2934 # convert config value to boolean: 'true' or 'false'
2935 # no value, number > 0, 'true' and 'yes' values are true
2936 # rest of values are treated as false (never as error)
2937 sub config_to_bool {
2938 my $val = shift;
2940 return 1 if !defined $val; # section.key
2942 # strip leading and trailing whitespace
2943 $val =~ s/^\s+//;
2944 $val =~ s/\s+$//;
2946 return (($val =~ /^\d+$/ && $val) || # section.key = 1
2947 ($val =~ /^(?:true|yes)$/i)); # section.key = true
2950 # convert config value to simple decimal number
2951 # an optional value suffix of 'k', 'm', or 'g' will cause the value
2952 # to be multiplied by 1024, 1048576, or 1073741824
2953 sub config_to_int {
2954 my $val = shift;
2956 # strip leading and trailing whitespace
2957 $val =~ s/^\s+//;
2958 $val =~ s/\s+$//;
2960 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
2961 $unit = lc($unit);
2962 # unknown unit is treated as 1
2963 return $num * ($unit eq 'g' ? 1073741824 :
2964 $unit eq 'm' ? 1048576 :
2965 $unit eq 'k' ? 1024 : 1);
2967 return $val;
2970 # convert config value to array reference, if needed
2971 sub config_to_multi {
2972 my $val = shift;
2974 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
2977 sub git_get_project_config {
2978 my ($key, $type) = @_;
2980 return unless defined $git_dir;
2982 # key sanity check
2983 return unless ($key);
2984 # only subsection, if exists, is case sensitive,
2985 # and not lowercased by 'git config -z -l'
2986 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
2987 $lo =~ s/_//g;
2988 $key = join(".", lc($hi), $mi, lc($lo));
2989 return if ($lo =~ /\W/ || $hi =~ /\W/);
2990 } else {
2991 $key = lc($key);
2992 $key =~ s/_//g;
2993 return if ($key =~ /\W/);
2995 $key =~ s/^gitweb\.//;
2997 # type sanity check
2998 if (defined $type) {
2999 $type =~ s/^--//;
3000 $type = undef
3001 unless ($type eq 'bool' || $type eq 'int');
3004 # get config
3005 if (!defined $config_file ||
3006 $config_file ne "$git_dir/config") {
3007 %config = git_parse_project_config('gitweb');
3008 $config_file = "$git_dir/config";
3011 # check if config variable (key) exists
3012 return unless exists $config{"gitweb.$key"};
3014 # ensure given type
3015 if (!defined $type) {
3016 return $config{"gitweb.$key"};
3017 } elsif ($type eq 'bool') {
3018 # backward compatibility: 'git config --bool' returns true/false
3019 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
3020 } elsif ($type eq 'int') {
3021 return config_to_int($config{"gitweb.$key"});
3023 return $config{"gitweb.$key"};
3026 # get hash of given path at given ref
3027 sub git_get_hash_by_path {
3028 my $base = shift;
3029 my $path = shift || return undef;
3030 my $type = shift;
3032 $path =~ s,/+$,,;
3034 defined(my $fd = git_cmd_pipe "ls-tree", $base, "--", $path)
3035 or die_error(500, "Open git-ls-tree failed");
3036 my $line = to_utf8(scalar <$fd>);
3037 close $fd or return undef;
3039 if (!defined $line) {
3040 # there is no tree or hash given by $path at $base
3041 return undef;
3044 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3045 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
3046 if (defined $type && $type ne $2) {
3047 # type doesn't match
3048 return undef;
3050 return $3;
3053 # get path of entry with given hash at given tree-ish (ref)
3054 # used to get 'from' filename for combined diff (merge commit) for renames
3055 sub git_get_path_by_hash {
3056 my $base = shift || return;
3057 my $hash = shift || return;
3059 local $/ = "\0";
3061 defined(my $fd = git_cmd_pipe "ls-tree", '-r', '-t', '-z', $base)
3062 or return undef;
3063 while (my $line = to_utf8(scalar <$fd>)) {
3064 chomp $line;
3066 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
3067 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
3068 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
3069 close $fd;
3070 return $1;
3073 close $fd;
3074 return undef;
3077 ## ......................................................................
3078 ## git utility functions, directly accessing git repository
3080 # get the value of config variable either from file named as the variable
3081 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
3082 # configuration variable in the repository config file.
3083 sub git_get_file_or_project_config {
3084 my ($path, $name) = @_;
3086 $git_dir = "$projectroot/$path";
3087 open my $fd, '<', "$git_dir/$name"
3088 or return git_get_project_config($name);
3089 my $conf = to_utf8(scalar <$fd>);
3090 close $fd;
3091 if (defined $conf) {
3092 chomp $conf;
3094 return $conf;
3097 sub git_get_project_description {
3098 my $path = shift;
3099 return git_get_file_or_project_config($path, 'description');
3102 sub git_get_project_category {
3103 my $path = shift;
3104 return git_get_file_or_project_config($path, 'category');
3108 # supported formats:
3109 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
3110 # - if its contents is a number, use it as tag weight,
3111 # - otherwise add a tag with weight 1
3112 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
3113 # the same value multiple times increases tag weight
3114 # * `gitweb.ctag' multi-valued repo config variable
3115 sub git_get_project_ctags {
3116 my $project = shift;
3117 my $ctags = {};
3119 $git_dir = "$projectroot/$project";
3120 if (opendir my $dh, "$git_dir/ctags") {
3121 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
3122 foreach my $tagfile (@files) {
3123 open my $ct, '<', $tagfile
3124 or next;
3125 my $val = <$ct>;
3126 chomp $val if $val;
3127 close $ct;
3129 (my $ctag = $tagfile) =~ s#.*/##;
3130 $ctag = to_utf8($ctag);
3131 if ($val =~ /^\d+$/) {
3132 $ctags->{$ctag} = $val;
3133 } else {
3134 $ctags->{$ctag} = 1;
3137 closedir $dh;
3139 } elsif (open my $fh, '<', "$git_dir/ctags") {
3140 while (my $line = to_utf8(scalar <$fh>)) {
3141 chomp $line;
3142 $ctags->{$line}++ if $line;
3144 close $fh;
3146 } else {
3147 my $taglist = config_to_multi(git_get_project_config('ctag'));
3148 foreach my $tag (@$taglist) {
3149 $ctags->{$tag}++;
3153 return $ctags;
3156 # return hash, where keys are content tags ('ctags'),
3157 # and values are sum of weights of given tag in every project
3158 sub git_gather_all_ctags {
3159 my $projects = shift;
3160 my $ctags = {};
3162 foreach my $p (@$projects) {
3163 foreach my $ct (keys %{$p->{'ctags'}}) {
3164 $ctags->{$ct} += $p->{'ctags'}->{$ct};
3168 return $ctags;
3171 sub git_populate_project_tagcloud {
3172 my $ctags = shift;
3174 # First, merge different-cased tags; tags vote on casing
3175 my %ctags_lc;
3176 foreach (keys %$ctags) {
3177 $ctags_lc{lc $_}->{count} += $ctags->{$_};
3178 if (not $ctags_lc{lc $_}->{topcount}
3179 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
3180 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
3181 $ctags_lc{lc $_}->{topname} = $_;
3185 my $cloud;
3186 my $matched = $input_params{'ctag'};
3187 if (eval { require HTML::TagCloud; 1; }) {
3188 $cloud = HTML::TagCloud->new;
3189 foreach my $ctag (sort keys %ctags_lc) {
3190 # Pad the title with spaces so that the cloud looks
3191 # less crammed.
3192 my $title = esc_html($ctags_lc{$ctag}->{topname});
3193 $title =~ s/ /&nbsp;/g;
3194 $title =~ s/^/&nbsp;/g;
3195 $title =~ s/$/&nbsp;/g;
3196 if (defined $matched && $matched eq $ctag) {
3197 $title = qq(<span class="match">$title</span>);
3199 $cloud->add($title, href(project=>undef, ctag=>$ctag),
3200 $ctags_lc{$ctag}->{count});
3202 } else {
3203 $cloud = {};
3204 foreach my $ctag (keys %ctags_lc) {
3205 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
3206 if (defined $matched && $matched eq $ctag) {
3207 $title = qq(<span class="match">$title</span>);
3209 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
3210 $cloud->{$ctag}{ctag} =
3211 $cgi->a({-href=>href(project=>undef, ctag=>$ctag)}, $title);
3214 return $cloud;
3217 sub git_show_project_tagcloud {
3218 my ($cloud, $count) = @_;
3219 if (ref $cloud eq 'HTML::TagCloud') {
3220 return $cloud->html_and_css($count);
3221 } else {
3222 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
3223 return
3224 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
3225 join (', ', map {
3226 $cloud->{$_}->{'ctag'}
3227 } splice(@tags, 0, $count)) .
3228 '</div>';
3232 sub git_get_project_url_list {
3233 my $path = shift;
3235 $git_dir = "$projectroot/$path";
3236 open my $fd, '<', "$git_dir/cloneurl"
3237 or return wantarray ?
3238 @{ config_to_multi(git_get_project_config('url')) } :
3239 config_to_multi(git_get_project_config('url'));
3240 my @git_project_url_list = map { chomp; to_utf8($_) } <$fd>;
3241 close $fd;
3243 return wantarray ? @git_project_url_list : \@git_project_url_list;
3246 sub git_get_projects_list {
3247 my $filter = shift || '';
3248 my $paranoid = shift;
3249 my @list;
3251 if (-d $projects_list) {
3252 # search in directory
3253 my $dir = $projects_list;
3254 # remove the trailing "/"
3255 $dir =~ s!/+$!!;
3256 my $pfxlen = length("$dir");
3257 my $pfxdepth = ($dir =~ tr!/!!);
3258 # when filtering, search only given subdirectory
3259 if ($filter && !$paranoid) {
3260 $dir .= "/$filter";
3261 $dir =~ s!/+$!!;
3264 File::Find::find({
3265 follow_fast => 1, # follow symbolic links
3266 follow_skip => 2, # ignore duplicates
3267 dangling_symlinks => 0, # ignore dangling symlinks, silently
3268 wanted => sub {
3269 # global variables
3270 our $project_maxdepth;
3271 our $projectroot;
3272 # skip project-list toplevel, if we get it.
3273 return if (m!^[/.]$!);
3274 # only directories can be git repositories
3275 return unless (-d $_);
3276 # don't traverse too deep (Find is super slow on os x)
3277 # $project_maxdepth excludes depth of $projectroot
3278 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3279 $File::Find::prune = 1;
3280 return;
3283 my $path = substr($File::Find::name, $pfxlen + 1);
3284 # paranoidly only filter here
3285 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3286 next;
3288 # we check related file in $projectroot
3289 if (check_export_ok("$projectroot/$path")) {
3290 push @list, { path => $path };
3291 $File::Find::prune = 1;
3294 }, "$dir");
3296 } elsif (-f $projects_list) {
3297 # read from file(url-encoded):
3298 # 'git%2Fgit.git Linus+Torvalds'
3299 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3300 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3301 open my $fd, '<', $projects_list or return;
3302 PROJECT:
3303 while (my $line = <$fd>) {
3304 chomp $line;
3305 my ($path, $owner) = split ' ', $line;
3306 $path = unescape($path);
3307 $owner = unescape($owner);
3308 if (!defined $path) {
3309 next;
3311 # if $filter is rpovided, check if $path begins with $filter
3312 if ($filter && $path !~ m!^\Q$filter\E/!) {
3313 next;
3315 if (check_export_ok("$projectroot/$path")) {
3316 my $pr = {
3317 path => $path
3319 if ($owner) {
3320 $pr->{'owner'} = to_utf8($owner);
3322 push @list, $pr;
3325 close $fd;
3327 return @list;
3330 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3331 # as side effects it sets 'forks' field to list of forks for forked projects
3332 sub filter_forks_from_projects_list {
3333 my $projects = shift;
3335 my %trie; # prefix tree of directories (path components)
3336 # generate trie out of those directories that might contain forks
3337 foreach my $pr (@$projects) {
3338 my $path = $pr->{'path'};
3339 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3340 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3341 next unless ($path); # skip '.git' repository: tests, git-instaweb
3342 next unless (-d "$projectroot/$path"); # containing directory exists
3343 $pr->{'forks'} = []; # there can be 0 or more forks of project
3345 # add to trie
3346 my @dirs = split('/', $path);
3347 # walk the trie, until either runs out of components or out of trie
3348 my $ref = \%trie;
3349 while (scalar @dirs &&
3350 exists($ref->{$dirs[0]})) {
3351 $ref = $ref->{shift @dirs};
3353 # create rest of trie structure from rest of components
3354 foreach my $dir (@dirs) {
3355 $ref = $ref->{$dir} = {};
3357 # create end marker, store $pr as a data
3358 $ref->{''} = $pr if (!exists $ref->{''});
3361 # filter out forks, by finding shortest prefix match for paths
3362 my @filtered;
3363 PROJECT:
3364 foreach my $pr (@$projects) {
3365 # trie lookup
3366 my $ref = \%trie;
3367 DIR:
3368 foreach my $dir (split('/', $pr->{'path'})) {
3369 if (exists $ref->{''}) {
3370 # found [shortest] prefix, is a fork - skip it
3371 push @{$ref->{''}{'forks'}}, $pr;
3372 next PROJECT;
3374 if (!exists $ref->{$dir}) {
3375 # not in trie, cannot have prefix, not a fork
3376 push @filtered, $pr;
3377 next PROJECT;
3379 # If the dir is there, we just walk one step down the trie.
3380 $ref = $ref->{$dir};
3382 # we ran out of trie
3383 # (shouldn't happen: it's either no match, or end marker)
3384 push @filtered, $pr;
3387 return @filtered;
3390 # note: fill_project_list_info must be run first,
3391 # for 'descr_long' and 'ctags' to be filled
3392 sub search_projects_list {
3393 my ($projlist, %opts) = @_;
3394 my $tagfilter = $opts{'tagfilter'};
3395 my $search_re = $opts{'search_regexp'};
3397 return @$projlist
3398 unless ($tagfilter || $search_re);
3400 # searching projects require filling to be run before it;
3401 fill_project_list_info($projlist,
3402 $tagfilter ? 'ctags' : (),
3403 $search_re ? ('path', 'descr') : ());
3404 my @projects;
3405 PROJECT:
3406 foreach my $pr (@$projlist) {
3408 if ($tagfilter) {
3409 next unless ref($pr->{'ctags'}) eq 'HASH';
3410 next unless
3411 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3414 if ($search_re) {
3415 next unless
3416 $pr->{'path'} =~ /$search_re/ ||
3417 $pr->{'descr_long'} =~ /$search_re/;
3420 push @projects, $pr;
3423 return @projects;
3426 our $gitweb_project_owner = undef;
3427 sub git_get_project_list_from_file {
3429 return if (defined $gitweb_project_owner);
3431 $gitweb_project_owner = {};
3432 # read from file (url-encoded):
3433 # 'git%2Fgit.git Linus+Torvalds'
3434 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3435 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3436 if (-f $projects_list) {
3437 open(my $fd, '<', $projects_list);
3438 while (my $line = <$fd>) {
3439 chomp $line;
3440 my ($pr, $ow) = split ' ', $line;
3441 $pr = unescape($pr);
3442 $ow = unescape($ow);
3443 $gitweb_project_owner->{$pr} = to_utf8($ow);
3445 close $fd;
3449 sub git_get_project_owner {
3450 my $project = shift;
3451 my $owner;
3453 return undef unless $project;
3454 $git_dir = "$projectroot/$project";
3456 if (!defined $gitweb_project_owner) {
3457 git_get_project_list_from_file();
3460 if (exists $gitweb_project_owner->{$project}) {
3461 $owner = $gitweb_project_owner->{$project};
3463 if (!defined $owner){
3464 $owner = git_get_project_config('owner');
3466 if (!defined $owner) {
3467 $owner = get_file_owner("$git_dir");
3470 return $owner;
3473 sub git_get_last_activity {
3474 my ($path) = @_;
3475 my $fd;
3477 $git_dir = "$projectroot/$path";
3478 defined($fd = git_cmd_pipe 'for-each-ref',
3479 '--format=%(committer)',
3480 '--sort=-committerdate',
3481 '--count=1',
3482 map { "refs/$_" } get_branch_refs ()) or return;
3483 my $most_recent = <$fd>;
3484 close $fd or return;
3485 if (defined $most_recent &&
3486 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3487 my $timestamp = $1;
3488 my $age = time - $timestamp;
3489 return ($age, age_string($age));
3491 return (undef, undef);
3494 # Implementation note: when a single remote is wanted, we cannot use 'git
3495 # remote show -n' because that command always work (assuming it's a remote URL
3496 # if it's not defined), and we cannot use 'git remote show' because that would
3497 # try to make a network roundtrip. So the only way to find if that particular
3498 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3499 # and when we find what we want.
3500 sub git_get_remotes_list {
3501 my $wanted = shift;
3502 my %remotes = ();
3504 my $fd = git_cmd_pipe 'remote', '-v';
3505 return unless $fd;
3506 while (my $remote = to_utf8(scalar <$fd>)) {
3507 chomp $remote;
3508 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
3509 next if $wanted and not $remote eq $wanted;
3510 my ($url, $key) = ($1, $2);
3512 $remotes{$remote} ||= { 'heads' => () };
3513 $remotes{$remote}{$key} = $url;
3515 close $fd or return;
3516 return wantarray ? %remotes : \%remotes;
3519 # Takes a hash of remotes as first parameter and fills it by adding the
3520 # available remote heads for each of the indicated remotes.
3521 sub fill_remote_heads {
3522 my $remotes = shift;
3523 my @heads = map { "remotes/$_" } keys %$remotes;
3524 my @remoteheads = git_get_heads_list(undef, @heads);
3525 foreach my $remote (keys %$remotes) {
3526 $remotes->{$remote}{'heads'} = [ grep {
3527 $_->{'name'} =~ s!^$remote/!!
3528 } @remoteheads ];
3532 sub git_get_references {
3533 my $type = shift || "";
3534 my %refs;
3535 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
3536 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
3537 defined(my $fd = git_cmd_pipe "show-ref", "--dereference",
3538 ($type ? ("--", "refs/$type") : ())) # use -- <pattern> if $type
3539 or return;
3541 while (my $line = to_utf8(scalar <$fd>)) {
3542 chomp $line;
3543 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
3544 if (defined $refs{$1}) {
3545 push @{$refs{$1}}, $2;
3546 } else {
3547 $refs{$1} = [ $2 ];
3551 close $fd or return;
3552 return \%refs;
3555 sub git_get_rev_name_tags {
3556 my $hash = shift || return undef;
3558 defined(my $fd = git_cmd_pipe "name-rev", "--tags", $hash)
3559 or return;
3560 my $name_rev = to_utf8(scalar <$fd>);
3561 close $fd;
3563 if ($name_rev =~ m|^$hash tags/(.*)$|) {
3564 return $1;
3565 } else {
3566 # catches also '$hash undefined' output
3567 return undef;
3571 ## ----------------------------------------------------------------------
3572 ## parse to hash functions
3574 sub parse_date {
3575 my $epoch = shift;
3576 my $tz = shift || "-0000";
3578 my %date;
3579 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
3580 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
3581 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
3582 $date{'hour'} = $hour;
3583 $date{'minute'} = $min;
3584 $date{'mday'} = $mday;
3585 $date{'day'} = $days[$wday];
3586 $date{'month'} = $months[$mon];
3587 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
3588 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
3589 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
3590 $mday, $months[$mon], $hour ,$min;
3591 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
3592 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
3594 my ($tz_sign, $tz_hour, $tz_min) =
3595 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
3596 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
3597 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
3598 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
3599 $date{'hour_local'} = $hour;
3600 $date{'minute_local'} = $min;
3601 $date{'tz_local'} = $tz;
3602 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
3603 1900+$year, $mon+1, $mday,
3604 $hour, $min, $sec, $tz);
3605 return %date;
3608 sub parse_tag {
3609 my $tag_id = shift;
3610 my %tag;
3611 my @comment;
3613 defined(my $fd = git_cmd_pipe "cat-file", "tag", $tag_id) or return;
3614 $tag{'id'} = $tag_id;
3615 while (my $line = to_utf8(scalar <$fd>)) {
3616 chomp $line;
3617 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
3618 $tag{'object'} = $1;
3619 } elsif ($line =~ m/^type (.+)$/) {
3620 $tag{'type'} = $1;
3621 } elsif ($line =~ m/^tag (.+)$/) {
3622 $tag{'name'} = $1;
3623 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
3624 $tag{'author'} = $1;
3625 $tag{'author_epoch'} = $2;
3626 $tag{'author_tz'} = $3;
3627 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3628 $tag{'author_name'} = $1;
3629 $tag{'author_email'} = $2;
3630 } else {
3631 $tag{'author_name'} = $tag{'author'};
3633 } elsif ($line =~ m/--BEGIN/) {
3634 push @comment, $line;
3635 last;
3636 } elsif ($line eq "") {
3637 last;
3640 push @comment, map(to_utf8($_), <$fd>);
3641 $tag{'comment'} = \@comment;
3642 close $fd or return;
3643 if (!defined $tag{'name'}) {
3644 return
3646 return %tag
3649 sub parse_commit_text {
3650 my ($commit_text, $withparents) = @_;
3651 my @commit_lines = split '\n', $commit_text;
3652 my %co;
3654 pop @commit_lines; # Remove '\0'
3656 if (! @commit_lines) {
3657 return;
3660 my $header = shift @commit_lines;
3661 if ($header !~ m/^[0-9a-fA-F]{40}/) {
3662 return;
3664 ($co{'id'}, my @parents) = split ' ', $header;
3665 while (my $line = shift @commit_lines) {
3666 last if $line eq "\n";
3667 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
3668 $co{'tree'} = $1;
3669 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
3670 push @parents, $1;
3671 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
3672 $co{'author'} = to_utf8($1);
3673 $co{'author_epoch'} = $2;
3674 $co{'author_tz'} = $3;
3675 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
3676 $co{'author_name'} = $1;
3677 $co{'author_email'} = $2;
3678 } else {
3679 $co{'author_name'} = $co{'author'};
3681 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
3682 $co{'committer'} = to_utf8($1);
3683 $co{'committer_epoch'} = $2;
3684 $co{'committer_tz'} = $3;
3685 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
3686 $co{'committer_name'} = $1;
3687 $co{'committer_email'} = $2;
3688 } else {
3689 $co{'committer_name'} = $co{'committer'};
3693 if (!defined $co{'tree'}) {
3694 return;
3696 $co{'parents'} = \@parents;
3697 $co{'parent'} = $parents[0];
3699 @commit_lines = map to_utf8($_), @commit_lines;
3700 foreach my $title (@commit_lines) {
3701 $title =~ s/^ //;
3702 if ($title ne "") {
3703 $co{'title'} = chop_str($title, 80, 5);
3704 # remove leading stuff of merges to make the interesting part visible
3705 if (length($title) > 50) {
3706 $title =~ s/^Automatic //;
3707 $title =~ s/^merge (of|with) /Merge ... /i;
3708 if (length($title) > 50) {
3709 $title =~ s/(http|rsync):\/\///;
3711 if (length($title) > 50) {
3712 $title =~ s/(master|www|rsync)\.//;
3714 if (length($title) > 50) {
3715 $title =~ s/kernel.org:?//;
3717 if (length($title) > 50) {
3718 $title =~ s/\/pub\/scm//;
3721 $co{'title_short'} = chop_str($title, 50, 5);
3722 last;
3725 if (! defined $co{'title'} || $co{'title'} eq "") {
3726 $co{'title'} = $co{'title_short'} = '(no commit message)';
3728 # remove added spaces
3729 foreach my $line (@commit_lines) {
3730 $line =~ s/^ //;
3732 $co{'comment'} = \@commit_lines;
3734 my $age = time - $co{'committer_epoch'};
3735 $co{'age'} = $age;
3736 $co{'age_string'} = age_string($age);
3737 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($co{'committer_epoch'});
3738 if ($age > 60*60*24*7*2) {
3739 $co{'age_string_date'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3740 $co{'age_string_age'} = $co{'age_string'};
3741 } else {
3742 $co{'age_string_date'} = $co{'age_string'};
3743 $co{'age_string_age'} = sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
3745 return %co;
3748 sub parse_commit {
3749 my ($commit_id) = @_;
3750 my %co;
3752 local $/ = "\0";
3754 defined(my $fd = git_cmd_pipe "rev-list",
3755 "--parents",
3756 "--header",
3757 "--max-count=1",
3758 $commit_id,
3759 "--")
3760 or die_error(500, "Open git-rev-list failed");
3761 %co = parse_commit_text(<$fd>, 1);
3762 close $fd;
3764 return %co;
3767 sub parse_commits {
3768 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
3769 my @cos;
3771 $maxcount ||= 1;
3772 $skip ||= 0;
3774 local $/ = "\0";
3776 defined(my $fd = git_cmd_pipe "rev-list",
3777 "--header",
3778 @args,
3779 ("--max-count=" . $maxcount),
3780 ("--skip=" . $skip),
3781 @extra_options,
3782 $commit_id,
3783 "--",
3784 ($filename ? ($filename) : ()))
3785 or die_error(500, "Open git-rev-list failed");
3786 while (my $line = <$fd>) {
3787 my %co = parse_commit_text($line);
3788 push @cos, \%co;
3790 close $fd;
3792 return wantarray ? @cos : \@cos;
3795 # parse line of git-diff-tree "raw" output
3796 sub parse_difftree_raw_line {
3797 my $line = shift;
3798 my %res;
3800 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
3801 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
3802 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
3803 $res{'from_mode'} = $1;
3804 $res{'to_mode'} = $2;
3805 $res{'from_id'} = $3;
3806 $res{'to_id'} = $4;
3807 $res{'status'} = $5;
3808 $res{'similarity'} = $6;
3809 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
3810 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
3811 } else {
3812 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
3815 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
3816 # combined diff (for merge commit)
3817 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
3818 $res{'nparents'} = length($1);
3819 $res{'from_mode'} = [ split(' ', $2) ];
3820 $res{'to_mode'} = pop @{$res{'from_mode'}};
3821 $res{'from_id'} = [ split(' ', $3) ];
3822 $res{'to_id'} = pop @{$res{'from_id'}};
3823 $res{'status'} = [ split('', $4) ];
3824 $res{'to_file'} = unquote($5);
3826 # 'c512b523472485aef4fff9e57b229d9d243c967f'
3827 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
3828 $res{'commit'} = $1;
3831 return wantarray ? %res : \%res;
3834 # wrapper: return parsed line of git-diff-tree "raw" output
3835 # (the argument might be raw line, or parsed info)
3836 sub parsed_difftree_line {
3837 my $line_or_ref = shift;
3839 if (ref($line_or_ref) eq "HASH") {
3840 # pre-parsed (or generated by hand)
3841 return $line_or_ref;
3842 } else {
3843 return parse_difftree_raw_line($line_or_ref);
3847 # parse line of git-ls-tree output
3848 sub parse_ls_tree_line {
3849 my $line = shift;
3850 my %opts = @_;
3851 my %res;
3853 if ($opts{'-l'}) {
3854 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
3855 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
3857 $res{'mode'} = $1;
3858 $res{'type'} = $2;
3859 $res{'hash'} = $3;
3860 $res{'size'} = $4;
3861 if ($opts{'-z'}) {
3862 $res{'name'} = $5;
3863 } else {
3864 $res{'name'} = unquote($5);
3866 } else {
3867 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3868 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
3870 $res{'mode'} = $1;
3871 $res{'type'} = $2;
3872 $res{'hash'} = $3;
3873 if ($opts{'-z'}) {
3874 $res{'name'} = $4;
3875 } else {
3876 $res{'name'} = unquote($4);
3880 return wantarray ? %res : \%res;
3883 # generates _two_ hashes, references to which are passed as 2 and 3 argument
3884 sub parse_from_to_diffinfo {
3885 my ($diffinfo, $from, $to, @parents) = @_;
3887 if ($diffinfo->{'nparents'}) {
3888 # combined diff
3889 $from->{'file'} = [];
3890 $from->{'href'} = [];
3891 fill_from_file_info($diffinfo, @parents)
3892 unless exists $diffinfo->{'from_file'};
3893 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
3894 $from->{'file'}[$i] =
3895 defined $diffinfo->{'from_file'}[$i] ?
3896 $diffinfo->{'from_file'}[$i] :
3897 $diffinfo->{'to_file'};
3898 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
3899 $from->{'href'}[$i] = href(action=>"blob",
3900 hash_base=>$parents[$i],
3901 hash=>$diffinfo->{'from_id'}[$i],
3902 file_name=>$from->{'file'}[$i]);
3903 } else {
3904 $from->{'href'}[$i] = undef;
3907 } else {
3908 # ordinary (not combined) diff
3909 $from->{'file'} = $diffinfo->{'from_file'};
3910 if ($diffinfo->{'status'} ne "A") { # not new (added) file
3911 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
3912 hash=>$diffinfo->{'from_id'},
3913 file_name=>$from->{'file'});
3914 } else {
3915 delete $from->{'href'};
3919 $to->{'file'} = $diffinfo->{'to_file'};
3920 if (!is_deleted($diffinfo)) { # file exists in result
3921 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
3922 hash=>$diffinfo->{'to_id'},
3923 file_name=>$to->{'file'});
3924 } else {
3925 delete $to->{'href'};
3929 ## ......................................................................
3930 ## parse to array of hashes functions
3932 sub git_get_heads_list {
3933 my ($limit, @classes) = @_;
3934 @classes = get_branch_refs() unless @classes;
3935 my @patterns = map { "refs/$_" } @classes;
3936 my @headslist;
3938 defined(my $fd = git_cmd_pipe 'for-each-ref',
3939 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
3940 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
3941 @patterns)
3942 or return;
3943 while (my $line = to_utf8(scalar <$fd>)) {
3944 my %ref_item;
3946 chomp $line;
3947 my ($refinfo, $committerinfo) = split(/\0/, $line);
3948 my ($hash, $name, $title) = split(' ', $refinfo, 3);
3949 my ($committer, $epoch, $tz) =
3950 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
3951 $ref_item{'fullname'} = $name;
3952 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
3953 $name =~ s!^refs/($strip_refs|remotes)/!!;
3954 $ref_item{'name'} = $name;
3955 # for refs neither in 'heads' nor 'remotes' we want to
3956 # show their ref dir
3957 my $ref_dir = (defined $1) ? $1 : '';
3958 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
3959 $ref_item{'name'} .= ' (' . $ref_dir . ')';
3962 $ref_item{'id'} = $hash;
3963 $ref_item{'title'} = $title || '(no commit message)';
3964 $ref_item{'epoch'} = $epoch;
3965 if ($epoch) {
3966 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
3967 } else {
3968 $ref_item{'age'} = "unknown";
3971 push @headslist, \%ref_item;
3973 close $fd;
3975 return wantarray ? @headslist : \@headslist;
3978 sub git_get_tags_list {
3979 my $limit = shift;
3980 my @tagslist;
3982 defined(my $fd = git_cmd_pipe 'for-each-ref',
3983 ($limit ? '--count='.($limit+1) : ()), '--sort=-creatordate',
3984 '--format=%(objectname) %(objecttype) %(refname) '.
3985 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
3986 'refs/tags')
3987 or return;
3988 while (my $line = to_utf8(scalar <$fd>)) {
3989 my %ref_item;
3991 chomp $line;
3992 my ($refinfo, $creatorinfo) = split(/\0/, $line);
3993 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
3994 my ($creator, $epoch, $tz) =
3995 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
3996 $ref_item{'fullname'} = $name;
3997 $name =~ s!^refs/tags/!!;
3999 $ref_item{'type'} = $type;
4000 $ref_item{'id'} = $id;
4001 $ref_item{'name'} = $name;
4002 if ($type eq "tag") {
4003 $ref_item{'subject'} = $title;
4004 $ref_item{'reftype'} = $reftype;
4005 $ref_item{'refid'} = $refid;
4006 } else {
4007 $ref_item{'reftype'} = $type;
4008 $ref_item{'refid'} = $id;
4011 if ($type eq "tag" || $type eq "commit") {
4012 $ref_item{'epoch'} = $epoch;
4013 if ($epoch) {
4014 $ref_item{'age'} = age_string(time - $ref_item{'epoch'});
4015 } else {
4016 $ref_item{'age'} = "unknown";
4020 push @tagslist, \%ref_item;
4022 close $fd;
4024 return wantarray ? @tagslist : \@tagslist;
4027 ## ----------------------------------------------------------------------
4028 ## filesystem-related functions
4030 sub get_file_owner {
4031 my $path = shift;
4033 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
4034 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
4035 if (!defined $gcos) {
4036 return undef;
4038 my $owner = $gcos;
4039 $owner =~ s/[,;].*$//;
4040 return to_utf8($owner);
4043 # assume that file exists
4044 sub insert_file {
4045 my $filename = shift;
4047 open my $fd, '<', $filename;
4048 while (<$fd>) {
4049 print to_utf8($_);
4051 close $fd;
4054 ## ......................................................................
4055 ## mimetype related functions
4057 sub mimetype_guess_file {
4058 my $filename = shift;
4059 my $mimemap = shift;
4060 my $rawmode = shift;
4061 -r $mimemap or return undef;
4063 my %mimemap;
4064 open(my $mh, '<', $mimemap) or return undef;
4065 while (<$mh>) {
4066 next if m/^#/; # skip comments
4067 my ($mimetype, @exts) = split(/\s+/);
4068 foreach my $ext (@exts) {
4069 $mimemap{$ext} = $mimetype;
4072 close($mh);
4074 my ($ext, $ans);
4075 $ext = $1 if $filename =~ /\.([^.]*)$/;
4076 $ans = $mimemap{$ext} if $ext;
4077 if (defined $ans) {
4078 my $l = lc($ans);
4079 $ans = 'text/html' if $l eq 'application/xhtml+xml';
4080 if (!$rawmode) {
4081 $ans = 'text/xml' if $l =~ m!^application/[^\s:;,=]+\+xml$! ||
4082 $l eq 'image/svg+xml' ||
4083 $l eq 'application/xml-dtd' ||
4084 $l eq 'application/xml-external-parsed-entity';
4087 return $ans;
4090 sub mimetype_guess {
4091 my $filename = shift;
4092 my $rawmode = shift;
4093 my $mime;
4094 $filename =~ /\./ or return undef;
4096 if ($mimetypes_file) {
4097 my $file = $mimetypes_file;
4098 if ($file !~ m!^/!) { # if it is relative path
4099 # it is relative to project
4100 $file = "$projectroot/$project/$file";
4102 $mime = mimetype_guess_file($filename, $file, $rawmode);
4104 $mime ||= mimetype_guess_file($filename, '/etc/mime.types', $rawmode);
4105 return $mime;
4108 sub blob_mimetype {
4109 my $fd = shift;
4110 my $filename = shift;
4111 my $rawmode = shift;
4112 my $mime;
4114 # The -T/-B file operators produce the wrong result unless a perlio
4115 # layer is present when the file handle is a pipe that delivers less
4116 # than 512 bytes of data before reaching EOF.
4118 # If we are running in a Perl that uses the stdio layer rather than the
4119 # unix+perlio layers we will end up adding a perlio layer on top of the
4120 # stdio layer and get a second level of buffering. This is harmless
4121 # and it makes the -T/-B file operators work properly in all cases.
4123 binmode $fd, ":perlio" or die_error(500, "Adding perlio layer failed")
4124 unless grep /^perlio$/, PerlIO::get_layers($fd);
4126 $mime = mimetype_guess($filename, $rawmode) if defined $filename;
4128 if (!$mime && $filename) {
4129 if ($filename =~ m/\.html?$/i) {
4130 $mime = 'text/html';
4131 } elsif ($filename =~ m/\.xht(?:ml)?$/i) {
4132 $mime = 'text/html';
4133 } elsif ($filename =~ m/\.te?xt?$/i) {
4134 $mime = 'text/plain';
4135 } elsif ($filename =~ m/\.(?:markdown|md)$/i) {
4136 $mime = 'text/plain';
4137 } elsif ($filename =~ m/\.png$/i) {
4138 $mime = 'image/png';
4139 } elsif ($filename =~ m/\.gif$/i) {
4140 $mime = 'image/gif';
4141 } elsif ($filename =~ m/\.jpe?g$/i) {
4142 $mime = 'image/jpeg';
4143 } elsif ($filename =~ m/\.svgz?$/i) {
4144 $mime = 'image/svg+xml';
4148 # just in case
4149 return $default_blob_plain_mimetype || 'application/octet-stream' unless $fd || $mime;
4151 $mime = -T $fd ? 'text/plain' : 'application/octet-stream' unless $mime;
4153 return $mime;
4156 sub is_ascii {
4157 use bytes;
4158 my $data = shift;
4159 return scalar($data =~ /^[\x00-\x7f]*$/);
4162 sub is_valid_utf8 {
4163 my $data = shift;
4164 return utf8::decode($data);
4167 sub extract_html_charset {
4168 return undef unless $_[0] && "$_[0]</head>" =~ m#<head(?:\s+[^>]*)?(?<!/)>(.*?)</head\s*>#is;
4169 my $head = $1;
4170 return $2 if $head =~ m#<meta\s+charset\s*=\s*(['"])\s*([a-z0-9(:)_.+-]+)\s*\1\s*/?>#is;
4171 while ($head =~ m#<meta\s+(http-equiv|content)\s*=\s*(['"])\s*([^\2]+?)\s*\2\s*(http-equiv|content)\s*=\s*(['"])\s*([^\5]+?)\s*\5\s*/?>#sig) {
4172 my %kv = (lc($1) => $3, lc($4) => $6);
4173 my ($he, $c) = (lc($kv{'http-equiv'}), $kv{'content'});
4174 return $1 if $he && $c && $he eq 'content-type' &&
4175 $c =~ m!\s*text/html\s*;\s*charset\s*=\s*([a-z0-9(:)_.+-]+)\s*$!is;
4177 return undef;
4180 sub blob_contenttype {
4181 my ($fd, $file_name, $type) = @_;
4183 $type ||= blob_mimetype($fd, $file_name, 1);
4184 return $type unless $type =~ m!^text/.+!i;
4185 my ($leader, $charset, $htmlcharset);
4186 if ($fd && read($fd, $leader, 32768)) {{
4187 $charset='US-ASCII' if is_ascii($leader);
4188 return ("$type; charset=UTF-8", $leader) if !$charset && is_valid_utf8($leader);
4189 $charset='ISO-8859-1' unless $charset;
4190 $htmlcharset = extract_html_charset($leader) if $type eq 'text/html';
4191 if ($htmlcharset && $charset ne 'US-ASCII') {
4192 $htmlcharset = undef if $htmlcharset =~ /^(?:utf-8|us-ascii)$/i
4195 return ("$type; charset=$htmlcharset", $leader) if $htmlcharset;
4196 my $defcharset = $default_text_plain_charset || '';
4197 $defcharset =~ s/^\s+//;
4198 $defcharset =~ s/\s+$//;
4199 $defcharset = '' if $charset && $charset ne 'US-ASCII' && $defcharset =~ /^(?:utf-8|us-ascii)$/i;
4200 return ("$type; charset=" . ($defcharset || 'ISO-8859-1'), $leader);
4203 # peek the first upto 128 bytes off a file handle
4204 sub peek128bytes {
4205 my $fd = shift;
4207 use IO::Handle;
4208 use bytes;
4210 my $prefix128;
4211 return '' unless $fd && read($fd, $prefix128, 128);
4213 # In the general case, we're guaranteed only to be able to ungetc one
4214 # character (provided, of course, we actually got a character first).
4216 # However, we know:
4218 # 1) we are dealing with a :perlio layer since blob_mimetype will have
4219 # already been called at least once on the file handle before us
4221 # 2) we have an $fd positioned at the start of the input stream and
4222 # therefore know we were positioned at a buffer boundary before
4223 # reading the initial upto 128 bytes
4225 # 3) the buffer size is at least 512 bytes
4227 # 4) we are careful to only unget raw bytes
4229 # 5) we are attempting to unget exactly the same number of bytes we got
4231 # Given the above conditions we will ALWAYS be able to safely unget
4232 # the $prefix128 value we just got.
4234 # In fact, we could read up to 511 bytes and still be sure.
4235 # (Reading 512 might pop us into the next internal buffer, but probably
4236 # not since that could break the always able to unget at least the one
4237 # you just got guarantee.)
4239 map {$fd->ungetc(ord($_))} reverse(split //, $prefix128);
4241 return $prefix128;
4244 # guess file syntax for syntax highlighting; return undef if no highlighting
4245 # the name of syntax can (in the future) depend on syntax highlighter used
4246 sub guess_file_syntax {
4247 my ($fd, $mimetype, $file_name) = @_;
4248 return undef unless $fd && defined $file_name &&
4249 defined $mimetype && $mimetype =~ m!^text/.+!i;
4250 my $basename = basename($file_name, '.in');
4251 return $highlight_basename{$basename}
4252 if exists $highlight_basename{$basename};
4254 # Peek to see if there's a shebang or xml line.
4255 # We always operate on bytes when testing this.
4257 use bytes;
4258 my $shebang = peek128bytes($fd);
4259 if (length($shebang) >= 4 && $shebang =~ /^#!/) { # 4 would be '#!/x'
4260 foreach my $key (keys %highlight_shebang) {
4261 my $ar = ref($highlight_shebang{$key}) ?
4262 $highlight_shebang{$key} :
4263 [$highlight_shebang{key}];
4264 map {return $key if $shebang =~ /$_/} @$ar;
4267 return 'xml' if $shebang =~ m!^\s*<\?xml\s!; # "xml" must be lowercase
4270 $basename =~ /\.([^.]*)$/;
4271 my $ext = $1 or return undef;
4272 return $highlight_ext{$ext}
4273 if exists $highlight_ext{$ext};
4275 return undef;
4278 # run highlighter and return FD of its output,
4279 # or return original FD if no highlighting
4280 sub run_highlighter {
4281 my ($fd, $syntax) = @_;
4282 return $fd unless $fd && !eof($fd) && defined $highlight_bin && defined $syntax;
4284 defined(my $hifd = cmd_pipe $posix_shell_bin, '-c',
4285 quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
4286 quote_command($highlight_bin).
4287 " --replace-tabs=8 --fragment --syntax $syntax")
4288 or die_error(500, "Couldn't open file or run syntax highlighter");
4289 if (eof $hifd) {
4290 # just in case, should not happen as we tested !eof($fd) above
4291 return $fd if close($hifd);
4293 # should not happen
4294 !$! or die_error(500, "Couldn't close syntax highighter pipe");
4296 # leaving us with the only possibility a non-zero exit status (possibly a signal);
4297 # instead of dying horribly on this, just skip the highlighting
4298 # but do output a message about it to STDERR that will end up in the log
4299 print STDERR "warning: skipping failed highlight for --syntax $syntax: ".
4300 sprintf("child exit status 0x%x\n", $?);
4301 return $fd
4303 close $fd;
4304 return ($hifd, 1);
4307 ## ======================================================================
4308 ## functions printing HTML: header, footer, error page
4310 sub get_page_title {
4311 my $title = to_utf8($site_name);
4313 unless (defined $project) {
4314 if (defined $project_filter) {
4315 $title .= " - projects in '" . esc_path($project_filter) . "'";
4317 return $title;
4319 $title .= " - " . to_utf8($project);
4321 return $title unless (defined $action);
4322 $title .= "/$action"; # $action is US-ASCII (7bit ASCII)
4324 return $title unless (defined $file_name);
4325 $title .= " - " . esc_path($file_name);
4326 if ($action eq "tree" && $file_name !~ m|/$|) {
4327 $title .= "/";
4330 return $title;
4333 sub get_content_type_html {
4334 # require explicit support from the UA if we are to send the page as
4335 # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
4336 # we have to do this because MSIE sometimes globs '*/*', pretending to
4337 # support xhtml+xml but choking when it gets what it asked for.
4338 if (defined $cgi->http('HTTP_ACCEPT') &&
4339 $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
4340 $cgi->Accept('application/xhtml+xml') != 0) {
4341 return 'application/xhtml+xml';
4342 } else {
4343 return 'text/html';
4347 sub print_feed_meta {
4348 if (defined $project) {
4349 my %href_params = get_feed_info();
4350 if (!exists $href_params{'-title'}) {
4351 $href_params{'-title'} = 'log';
4354 foreach my $format (qw(RSS Atom)) {
4355 my $type = lc($format);
4356 my %link_attr = (
4357 '-rel' => 'alternate',
4358 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
4359 '-type' => "application/$type+xml"
4362 $href_params{'extra_options'} = undef;
4363 $href_params{'action'} = $type;
4364 $link_attr{'-href'} = href(%href_params);
4365 print "<link ".
4366 "rel=\"$link_attr{'-rel'}\" ".
4367 "title=\"$link_attr{'-title'}\" ".
4368 "href=\"$link_attr{'-href'}\" ".
4369 "type=\"$link_attr{'-type'}\" ".
4370 "/>\n";
4372 $href_params{'extra_options'} = '--no-merges';
4373 $link_attr{'-href'} = href(%href_params);
4374 $link_attr{'-title'} .= ' (no merges)';
4375 print "<link ".
4376 "rel=\"$link_attr{'-rel'}\" ".
4377 "title=\"$link_attr{'-title'}\" ".
4378 "href=\"$link_attr{'-href'}\" ".
4379 "type=\"$link_attr{'-type'}\" ".
4380 "/>\n";
4383 } else {
4384 printf('<link rel="alternate" title="%s projects list" '.
4385 'href="%s" type="text/plain; charset=utf-8" />'."\n",
4386 esc_attr($site_name), href(project=>undef, action=>"project_index"));
4387 printf('<link rel="alternate" title="%s projects feeds" '.
4388 'href="%s" type="text/x-opml" />'."\n",
4389 esc_attr($site_name), href(project=>undef, action=>"opml"));
4393 sub print_header_links {
4394 my $status = shift;
4396 # print out each stylesheet that exist, providing backwards capability
4397 # for those people who defined $stylesheet in a config file
4398 if (defined $stylesheet) {
4399 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4400 } else {
4401 foreach my $stylesheet (@stylesheets) {
4402 next unless $stylesheet;
4403 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4406 print_feed_meta()
4407 if ($status eq '200 OK');
4408 if (defined $favicon) {
4409 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
4413 sub print_nav_breadcrumbs_path {
4414 my $dirprefix = undef;
4415 while (my $part = shift) {
4416 $dirprefix .= "/" if defined $dirprefix;
4417 $dirprefix .= $part;
4418 print $cgi->a({-href => href(project => undef,
4419 project_filter => $dirprefix,
4420 action => "project_list")},
4421 esc_html($part)) . " / ";
4425 sub print_nav_breadcrumbs {
4426 my %opts = @_;
4428 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4429 print $cgi->a({-href => esc_url($crumb->[1])}, $crumb->[0]) . " / ";
4431 if (defined $project) {
4432 my @dirname = split '/', $project;
4433 my $projectbasename = pop @dirname;
4434 print_nav_breadcrumbs_path(@dirname);
4435 print $cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));
4436 if (defined $action) {
4437 my $action_print = $action ;
4438 if (defined $opts{-action_extra}) {
4439 $action_print = $cgi->a({-href => href(action=>$action)},
4440 $action);
4442 print " / $action_print";
4444 if (defined $opts{-action_extra}) {
4445 print " / $opts{-action_extra}";
4447 print "\n";
4448 } elsif (defined $project_filter) {
4449 print_nav_breadcrumbs_path(split '/', $project_filter);
4453 sub print_search_form {
4454 if (!defined $searchtext) {
4455 $searchtext = "";
4457 my $search_hash;
4458 if (defined $hash_base) {
4459 $search_hash = $hash_base;
4460 } elsif (defined $hash) {
4461 $search_hash = $hash;
4462 } else {
4463 $search_hash = "HEAD";
4465 my $action = $my_uri;
4466 my $use_pathinfo = gitweb_check_feature('pathinfo');
4467 if ($use_pathinfo) {
4468 $action .= "/".esc_url($project);
4470 print $cgi->start_form(-method => "get", -action => $action) .
4471 "<div class=\"search\">\n" .
4472 (!$use_pathinfo &&
4473 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
4474 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
4475 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
4476 $cgi->popup_menu(-name => 'st', -default => 'commit',
4477 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
4478 " " . $cgi->a({-href => href(action=>"search_help"),
4479 -title => "search help" }, "?") . " search:\n",
4480 $cgi->textfield(-name => "s", -value => $searchtext, -override => 1) . "\n" .
4481 "<span title=\"Extended regular expression\">" .
4482 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
4483 -checked => $search_use_regexp) .
4484 "</span>" .
4485 "</div>" .
4486 $cgi->end_form() . "\n";
4489 sub git_header_html {
4490 my $status = shift || "200 OK";
4491 my $expires = shift;
4492 my %opts = @_;
4494 my $title = get_page_title();
4495 my $content_type = get_content_type_html();
4496 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
4497 -status=> $status, -expires => $expires)
4498 unless ($opts{'-no_http_header'});
4499 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
4500 print <<EOF;
4501 <?xml version="1.0" encoding="utf-8"?>
4502 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4503 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
4504 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
4505 <!-- git core binaries version $git_version -->
4506 <head>
4507 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
4508 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
4509 <meta name="robots" content="index, nofollow"/>
4510 <title>$title</title>
4512 # the stylesheet, favicon etc urls won't work correctly with path_info
4513 # unless we set the appropriate base URL
4514 if ($ENV{'PATH_INFO'}) {
4515 print "<base href=\"".esc_url($base_url)."\" />\n";
4517 print_header_links($status);
4519 if (defined $site_html_head_string) {
4520 print to_utf8($site_html_head_string);
4523 print "</head>\n" .
4524 "<body>\n";
4526 if (defined $site_header && -f $site_header) {
4527 insert_file($site_header);
4530 print "<div class=\"page_header\">\n";
4531 if (defined $logo) {
4532 print $cgi->a({-href => esc_url($logo_url),
4533 -title => $logo_label},
4534 $cgi->img({-src => esc_url($logo),
4535 -width => 72, -height => 27,
4536 -alt => "git",
4537 -class => "logo"}));
4539 print_nav_breadcrumbs(%opts);
4540 print "</div>\n";
4542 my $have_search = gitweb_check_feature('search');
4543 if (defined $project && $have_search) {
4544 print_search_form();
4548 sub git_footer_html {
4549 my $feed_class = 'rss_logo';
4551 print "<div class=\"page_footer\">\n";
4552 if (defined $project) {
4553 my $descr = git_get_project_description($project);
4554 if (defined $descr) {
4555 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
4558 my %href_params = get_feed_info();
4559 if (!%href_params) {
4560 $feed_class .= ' generic';
4562 $href_params{'-title'} ||= 'log';
4564 foreach my $format (qw(RSS Atom)) {
4565 $href_params{'action'} = lc($format);
4566 print $cgi->a({-href => href(%href_params),
4567 -title => "$href_params{'-title'} $format feed",
4568 -class => $feed_class}, $format)."\n";
4571 } else {
4572 print $cgi->a({-href => href(project=>undef, action=>"opml",
4573 project_filter => $project_filter),
4574 -class => $feed_class}, "OPML") . " ";
4575 print $cgi->a({-href => href(project=>undef, action=>"project_index",
4576 project_filter => $project_filter),
4577 -class => $feed_class}, "TXT") . "\n";
4579 print "</div>\n"; # class="page_footer"
4581 if (defined $t0 && gitweb_check_feature('timed')) {
4582 print "<div id=\"generating_info\">\n";
4583 print 'This page took '.
4584 '<span id="generating_time" class="time_span">'.
4585 tv_interval($t0, [ gettimeofday() ]).
4586 ' seconds </span>'.
4587 ' and '.
4588 '<span id="generating_cmd">'.
4589 $number_of_git_cmds.
4590 '</span> git commands '.
4591 " to generate.\n";
4592 print "</div>\n"; # class="page_footer"
4595 if (defined $site_footer && -f $site_footer) {
4596 insert_file($site_footer);
4599 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
4600 if (defined $action &&
4601 $action eq 'blame_incremental') {
4602 print qq!<script type="text/javascript">\n!.
4603 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
4604 qq! "!. href() .qq!");\n!.
4605 qq!</script>\n!;
4606 } else {
4607 my ($jstimezone, $tz_cookie, $datetime_class) =
4608 gitweb_get_feature('javascript-timezone');
4610 print qq!<script type="text/javascript">\n!.
4611 qq!window.onload = function () {\n!;
4612 if (gitweb_check_feature('javascript-actions')) {
4613 print qq! fixLinks();\n!;
4615 if ($jstimezone && $tz_cookie && $datetime_class) {
4616 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
4617 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
4619 print qq!};\n!.
4620 qq!</script>\n!;
4623 print "</body>\n" .
4624 "</html>";
4627 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
4628 # Example: die_error(404, 'Hash not found')
4629 # By convention, use the following status codes (as defined in RFC 2616):
4630 # 400: Invalid or missing CGI parameters, or
4631 # requested object exists but has wrong type.
4632 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
4633 # this server or project.
4634 # 404: Requested object/revision/project doesn't exist.
4635 # 500: The server isn't configured properly, or
4636 # an internal error occurred (e.g. failed assertions caused by bugs), or
4637 # an unknown error occurred (e.g. the git binary died unexpectedly).
4638 # 503: The server is currently unavailable (because it is overloaded,
4639 # or down for maintenance). Generally, this is a temporary state.
4640 sub die_error {
4641 my $status = shift || 500;
4642 my $error = esc_html(shift) || "Internal Server Error";
4643 my $extra = shift;
4644 my %opts = @_;
4646 my %http_responses = (
4647 400 => '400 Bad Request',
4648 403 => '403 Forbidden',
4649 404 => '404 Not Found',
4650 500 => '500 Internal Server Error',
4651 503 => '503 Service Unavailable',
4653 git_header_html($http_responses{$status}, undef, %opts);
4654 print <<EOF;
4655 <div class="page_body">
4656 <br /><br />
4657 $status - $error
4658 <br />
4660 if (defined $extra) {
4661 print "<hr />\n" .
4662 "$extra\n";
4664 print "</div>\n";
4666 git_footer_html();
4667 goto DONE_GITWEB
4668 unless ($opts{'-error_handler'});
4671 ## ----------------------------------------------------------------------
4672 ## functions printing or outputting HTML: navigation
4674 sub git_print_page_nav {
4675 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
4676 $extra = '' if !defined $extra; # pager or formats
4678 my @navs = qw(summary shortlog log commit commitdiff tree);
4679 if ($suppress) {
4680 @navs = grep { $_ ne $suppress } @navs;
4683 my %arg = map { $_ => {action=>$_} } @navs;
4684 if (defined $head) {
4685 for (qw(commit commitdiff)) {
4686 $arg{$_}{'hash'} = $head;
4688 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
4689 for (qw(shortlog log)) {
4690 $arg{$_}{'hash'} = $head;
4695 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
4696 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
4698 my @actions = gitweb_get_feature('actions');
4699 my %repl = (
4700 '%' => '%',
4701 'n' => $project, # project name
4702 'f' => $git_dir, # project path within filesystem
4703 'h' => $treehead || '', # current hash ('h' parameter)
4704 'b' => $treebase || '', # hash base ('hb' parameter)
4706 while (@actions) {
4707 my ($label, $link, $pos) = splice(@actions,0,3);
4708 # insert
4709 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
4710 # munch munch
4711 $link =~ s/%([%nfhb])/$repl{$1}/g;
4712 $arg{$label}{'_href'} = $link;
4715 print "<div class=\"page_nav\">\n" .
4716 (join " | ",
4717 map { $_ eq $current ?
4718 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
4719 } @navs);
4720 print "<br/>\n$extra<br/>\n" .
4721 "</div>\n";
4724 # returns a submenu for the nagivation of the refs views (tags, heads,
4725 # remotes) with the current view disabled and the remotes view only
4726 # available if the feature is enabled
4727 sub format_ref_views {
4728 my ($current) = @_;
4729 my @ref_views = qw{tags heads};
4730 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
4731 return join " | ", map {
4732 $_ eq $current ? $_ :
4733 $cgi->a({-href => href(action=>$_)}, $_)
4734 } @ref_views
4737 sub format_paging_nav {
4738 my ($action, $page, $has_next_link) = @_;
4739 my $paging_nav;
4742 if ($page > 0) {
4743 $paging_nav .=
4744 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
4745 " &sdot; " .
4746 $cgi->a({-href => href(-replay=>1, page=>$page-1),
4747 -accesskey => "p", -title => "Alt-p"}, "prev");
4748 } else {
4749 $paging_nav .= "first &sdot; prev";
4752 if ($has_next_link) {
4753 $paging_nav .= " &sdot; " .
4754 $cgi->a({-href => href(-replay=>1, page=>$page+1),
4755 -accesskey => "n", -title => "Alt-n"}, "next");
4756 } else {
4757 $paging_nav .= " &sdot; next";
4760 return $paging_nav;
4763 ## ......................................................................
4764 ## functions printing or outputting HTML: div
4766 sub git_print_header_div {
4767 my ($action, $title, $hash, $hash_base) = @_;
4768 my %args = ();
4770 $args{'action'} = $action;
4771 $args{'hash'} = $hash if $hash;
4772 $args{'hash_base'} = $hash_base if $hash_base;
4774 print "<div class=\"header\">\n" .
4775 $cgi->a({-href => href(%args), -class => "title"},
4776 $title ? $title : $action) .
4777 "\n</div>\n";
4780 sub format_repo_url {
4781 my ($name, $url) = @_;
4782 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
4785 # Group output by placing it in a DIV element and adding a header.
4786 # Options for start_div() can be provided by passing a hash reference as the
4787 # first parameter to the function.
4788 # Options to git_print_header_div() can be provided by passing an array
4789 # reference. This must follow the options to start_div if they are present.
4790 # The content can be a scalar, which is output as-is, a scalar reference, which
4791 # is output after html escaping, an IO handle passed either as *handle or
4792 # *handle{IO}, or a function reference. In the latter case all following
4793 # parameters will be taken as argument to the content function call.
4794 sub git_print_section {
4795 my ($div_args, $header_args, $content);
4796 my $arg = shift;
4797 if (ref($arg) eq 'HASH') {
4798 $div_args = $arg;
4799 $arg = shift;
4801 if (ref($arg) eq 'ARRAY') {
4802 $header_args = $arg;
4803 $arg = shift;
4805 $content = $arg;
4807 print $cgi->start_div($div_args);
4808 git_print_header_div(@$header_args);
4810 if (ref($content) eq 'CODE') {
4811 $content->(@_);
4812 } elsif (ref($content) eq 'SCALAR') {
4813 print esc_html($$content);
4814 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
4815 while (<$content>) {
4816 print to_utf8($_);
4818 } elsif (!ref($content) && defined($content)) {
4819 print $content;
4822 print $cgi->end_div;
4825 sub format_timestamp_html {
4826 my $date = shift;
4827 my $strtime = $date->{'rfc2822'};
4829 my (undef, undef, $datetime_class) =
4830 gitweb_get_feature('javascript-timezone');
4831 if ($datetime_class) {
4832 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
4835 my $localtime_format = '(%02d:%02d %s)';
4836 if ($date->{'hour_local'} < 6) {
4837 $localtime_format = '(<span class="atnight">%02d:%02d</span> %s)';
4839 $strtime .= ' ' .
4840 sprintf($localtime_format,
4841 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
4843 return $strtime;
4846 # Outputs the author name and date in long form
4847 sub git_print_authorship {
4848 my $co = shift;
4849 my %opts = @_;
4850 my $tag = $opts{-tag} || 'div';
4851 my $author = $co->{'author_name'};
4853 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
4854 print "<$tag class=\"author_date\">" .
4855 format_search_author($author, "author", esc_html($author)) .
4856 " [".format_timestamp_html(\%ad)."]".
4857 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
4858 "</$tag>\n";
4861 # Outputs table rows containing the full author or committer information,
4862 # in the format expected for 'commit' view (& similar).
4863 # Parameters are a commit hash reference, followed by the list of people
4864 # to output information for. If the list is empty it defaults to both
4865 # author and committer.
4866 sub git_print_authorship_rows {
4867 my $co = shift;
4868 # too bad we can't use @people = @_ || ('author', 'committer')
4869 my @people = @_;
4870 @people = ('author', 'committer') unless @people;
4871 foreach my $who (@people) {
4872 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
4873 print "<tr><td>$who</td><td>" .
4874 format_search_author($co->{"${who}_name"}, $who,
4875 esc_html($co->{"${who}_name"})) . " " .
4876 format_search_author($co->{"${who}_email"}, $who,
4877 esc_html("<" . $co->{"${who}_email"} . ">")) .
4878 "</td><td rowspan=\"2\">" .
4879 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
4880 "</td></tr>\n" .
4881 "<tr>" .
4882 "<td></td><td>" .
4883 format_timestamp_html(\%wd) .
4884 "</td>" .
4885 "</tr>\n";
4889 sub git_print_page_path {
4890 my $name = shift;
4891 my $type = shift;
4892 my $hb = shift;
4895 print "<div class=\"page_path\">";
4896 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
4897 -title => 'tree root'}, to_utf8("[$project]"));
4898 print " / ";
4899 if (defined $name) {
4900 my @dirname = split '/', $name;
4901 my $basename = pop @dirname;
4902 my $fullname = '';
4904 foreach my $dir (@dirname) {
4905 $fullname .= ($fullname ? '/' : '') . $dir;
4906 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
4907 hash_base=>$hb),
4908 -title => $fullname}, esc_path($dir));
4909 print " / ";
4911 if (defined $type && $type eq 'blob') {
4912 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
4913 hash_base=>$hb),
4914 -title => $name}, esc_path($basename));
4915 } elsif (defined $type && $type eq 'tree') {
4916 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
4917 hash_base=>$hb),
4918 -title => $name}, esc_path($basename));
4919 print " / ";
4920 } else {
4921 print esc_path($basename);
4924 print "<br/></div>\n";
4927 sub git_print_log {
4928 my $log = shift;
4929 my %opts = @_;
4931 if ($opts{'-remove_title'}) {
4932 # remove title, i.e. first line of log
4933 shift @$log;
4935 # remove leading empty lines
4936 while (defined $log->[0] && $log->[0] eq "") {
4937 shift @$log;
4940 # print log
4941 my $skip_blank_line = 0;
4942 foreach my $line (@$log) {
4943 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
4944 if (! $opts{'-remove_signoff'}) {
4945 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
4946 $skip_blank_line = 1;
4948 next;
4951 if ($line =~ m,\s*([a-z]*link): (https?://\S+),i) {
4952 if (! $opts{'-remove_signoff'}) {
4953 print "<span class=\"signoff\">" . esc_html($1) . ": " .
4954 "<a href=\"" . esc_html($2) . "\">" . esc_html($2) . "</a>" .
4955 "</span><br/>\n";
4956 $skip_blank_line = 1;
4958 next;
4961 # print only one empty line
4962 # do not print empty line after signoff
4963 if ($line eq "") {
4964 next if ($skip_blank_line);
4965 $skip_blank_line = 1;
4966 } else {
4967 $skip_blank_line = 0;
4970 print format_log_line_html($line) . "<br/>\n";
4973 if ($opts{'-final_empty_line'}) {
4974 # end with single empty line
4975 print "<br/>\n" unless $skip_blank_line;
4979 # return link target (what link points to)
4980 sub git_get_link_target {
4981 my $hash = shift;
4982 my $link_target;
4984 # read link
4985 defined(my $fd = git_cmd_pipe "cat-file", "blob", $hash)
4986 or return;
4988 local $/ = undef;
4989 $link_target = to_utf8(scalar <$fd>);
4991 close $fd
4992 or return;
4994 return $link_target;
4997 # given link target, and the directory (basedir) the link is in,
4998 # return target of link relative to top directory (top tree);
4999 # return undef if it is not possible (including absolute links).
5000 sub normalize_link_target {
5001 my ($link_target, $basedir) = @_;
5003 # absolute symlinks (beginning with '/') cannot be normalized
5004 return if (substr($link_target, 0, 1) eq '/');
5006 # normalize link target to path from top (root) tree (dir)
5007 my $path;
5008 if ($basedir) {
5009 $path = $basedir . '/' . $link_target;
5010 } else {
5011 # we are in top (root) tree (dir)
5012 $path = $link_target;
5015 # remove //, /./, and /../
5016 my @path_parts;
5017 foreach my $part (split('/', $path)) {
5018 # discard '.' and ''
5019 next if (!$part || $part eq '.');
5020 # handle '..'
5021 if ($part eq '..') {
5022 if (@path_parts) {
5023 pop @path_parts;
5024 } else {
5025 # link leads outside repository (outside top dir)
5026 return;
5028 } else {
5029 push @path_parts, $part;
5032 $path = join('/', @path_parts);
5034 return $path;
5037 # print tree entry (row of git_tree), but without encompassing <tr> element
5038 sub git_print_tree_entry {
5039 my ($t, $basedir, $hash_base, $have_blame) = @_;
5041 my %base_key = ();
5042 $base_key{'hash_base'} = $hash_base if defined $hash_base;
5044 # The format of a table row is: mode list link. Where mode is
5045 # the mode of the entry, list is the name of the entry, an href,
5046 # and link is the action links of the entry.
5048 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
5049 if (exists $t->{'size'}) {
5050 print "<td class=\"size\">$t->{'size'}</td>\n";
5052 if ($t->{'type'} eq "blob") {
5053 print "<td class=\"list\">" .
5054 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
5055 file_name=>"$basedir$t->{'name'}", %base_key),
5056 -class => "list"}, esc_path($t->{'name'}));
5057 if (S_ISLNK(oct $t->{'mode'})) {
5058 my $link_target = git_get_link_target($t->{'hash'});
5059 if ($link_target) {
5060 my $norm_target = normalize_link_target($link_target, $basedir);
5061 if (defined $norm_target) {
5062 print " -> " .
5063 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
5064 file_name=>$norm_target),
5065 -title => $norm_target}, esc_path($link_target));
5066 } else {
5067 print " -> " . esc_path($link_target);
5071 print "</td>\n";
5072 print "<td class=\"link\">";
5073 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
5074 file_name=>"$basedir$t->{'name'}", %base_key)},
5075 "blob");
5076 if ($have_blame) {
5077 print " | " .
5078 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
5079 file_name=>"$basedir$t->{'name'}", %base_key)},
5080 "blame");
5082 if (defined $hash_base) {
5083 print " | " .
5084 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
5085 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
5086 "history");
5088 print " | " .
5089 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
5090 file_name=>"$basedir$t->{'name'}")},
5091 "raw");
5092 print "</td>\n";
5094 } elsif ($t->{'type'} eq "tree") {
5095 print "<td class=\"list\">";
5096 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
5097 file_name=>"$basedir$t->{'name'}",
5098 %base_key)},
5099 esc_path($t->{'name'}));
5100 print "</td>\n";
5101 print "<td class=\"link\">";
5102 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
5103 file_name=>"$basedir$t->{'name'}",
5104 %base_key)},
5105 "tree");
5106 if (defined $hash_base) {
5107 print " | " .
5108 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
5109 file_name=>"$basedir$t->{'name'}")},
5110 "history");
5112 print "</td>\n";
5113 } else {
5114 # unknown object: we can only present history for it
5115 # (this includes 'commit' object, i.e. submodule support)
5116 print "<td class=\"list\">" .
5117 esc_path($t->{'name'}) .
5118 "</td>\n";
5119 print "<td class=\"link\">";
5120 if (defined $hash_base) {
5121 print $cgi->a({-href => href(action=>"history",
5122 hash_base=>$hash_base,
5123 file_name=>"$basedir$t->{'name'}")},
5124 "history");
5126 print "</td>\n";
5130 ## ......................................................................
5131 ## functions printing large fragments of HTML
5133 # get pre-image filenames for merge (combined) diff
5134 sub fill_from_file_info {
5135 my ($diff, @parents) = @_;
5137 $diff->{'from_file'} = [ ];
5138 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
5139 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
5140 if ($diff->{'status'}[$i] eq 'R' ||
5141 $diff->{'status'}[$i] eq 'C') {
5142 $diff->{'from_file'}[$i] =
5143 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
5147 return $diff;
5150 # is current raw difftree line of file deletion
5151 sub is_deleted {
5152 my $diffinfo = shift;
5154 return $diffinfo->{'to_id'} eq ('0' x 40);
5157 # does patch correspond to [previous] difftree raw line
5158 # $diffinfo - hashref of parsed raw diff format
5159 # $patchinfo - hashref of parsed patch diff format
5160 # (the same keys as in $diffinfo)
5161 sub is_patch_split {
5162 my ($diffinfo, $patchinfo) = @_;
5164 return defined $diffinfo && defined $patchinfo
5165 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
5169 sub git_difftree_body {
5170 my ($difftree, $hash, @parents) = @_;
5171 my ($parent) = $parents[0];
5172 my $have_blame = gitweb_check_feature('blame');
5173 print "<div class=\"list_head\">\n";
5174 if ($#{$difftree} > 10) {
5175 print(($#{$difftree} + 1) . " files changed:\n");
5177 print "</div>\n";
5179 print "<table class=\"" .
5180 (@parents > 1 ? "combined " : "") .
5181 "diff_tree\">\n";
5183 # header only for combined diff in 'commitdiff' view
5184 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
5185 if ($has_header) {
5186 # table header
5187 print "<thead><tr>\n" .
5188 "<th></th><th></th>\n"; # filename, patchN link
5189 for (my $i = 0; $i < @parents; $i++) {
5190 my $par = $parents[$i];
5191 print "<th>" .
5192 $cgi->a({-href => href(action=>"commitdiff",
5193 hash=>$hash, hash_parent=>$par),
5194 -title => 'commitdiff to parent number ' .
5195 ($i+1) . ': ' . substr($par,0,7)},
5196 $i+1) .
5197 "&nbsp;</th>\n";
5199 print "</tr></thead>\n<tbody>\n";
5202 my $alternate = 1;
5203 my $patchno = 0;
5204 foreach my $line (@{$difftree}) {
5205 my $diff = parsed_difftree_line($line);
5207 if ($alternate) {
5208 print "<tr class=\"dark\">\n";
5209 } else {
5210 print "<tr class=\"light\">\n";
5212 $alternate ^= 1;
5214 if (exists $diff->{'nparents'}) { # combined diff
5216 fill_from_file_info($diff, @parents)
5217 unless exists $diff->{'from_file'};
5219 if (!is_deleted($diff)) {
5220 # file exists in the result (child) commit
5221 print "<td>" .
5222 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5223 file_name=>$diff->{'to_file'},
5224 hash_base=>$hash),
5225 -class => "list"}, esc_path($diff->{'to_file'})) .
5226 "</td>\n";
5227 } else {
5228 print "<td>" .
5229 esc_path($diff->{'to_file'}) .
5230 "</td>\n";
5233 if ($action eq 'commitdiff') {
5234 # link to patch
5235 $patchno++;
5236 print "<td class=\"link\">" .
5237 $cgi->a({-href => href(-anchor=>"patch$patchno")},
5238 "patch") .
5239 " | " .
5240 "</td>\n";
5243 my $has_history = 0;
5244 my $not_deleted = 0;
5245 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
5246 my $hash_parent = $parents[$i];
5247 my $from_hash = $diff->{'from_id'}[$i];
5248 my $from_path = $diff->{'from_file'}[$i];
5249 my $status = $diff->{'status'}[$i];
5251 $has_history ||= ($status ne 'A');
5252 $not_deleted ||= ($status ne 'D');
5254 if ($status eq 'A') {
5255 print "<td class=\"link\" align=\"right\"> | </td>\n";
5256 } elsif ($status eq 'D') {
5257 print "<td class=\"link\">" .
5258 $cgi->a({-href => href(action=>"blob",
5259 hash_base=>$hash,
5260 hash=>$from_hash,
5261 file_name=>$from_path)},
5262 "blob" . ($i+1)) .
5263 " | </td>\n";
5264 } else {
5265 if ($diff->{'to_id'} eq $from_hash) {
5266 print "<td class=\"link nochange\">";
5267 } else {
5268 print "<td class=\"link\">";
5270 print $cgi->a({-href => href(action=>"blobdiff",
5271 hash=>$diff->{'to_id'},
5272 hash_parent=>$from_hash,
5273 hash_base=>$hash,
5274 hash_parent_base=>$hash_parent,
5275 file_name=>$diff->{'to_file'},
5276 file_parent=>$from_path)},
5277 "diff" . ($i+1)) .
5278 " | </td>\n";
5282 print "<td class=\"link\">";
5283 if ($not_deleted) {
5284 print $cgi->a({-href => href(action=>"blob",
5285 hash=>$diff->{'to_id'},
5286 file_name=>$diff->{'to_file'},
5287 hash_base=>$hash)},
5288 "blob");
5289 print " | " if ($has_history);
5291 if ($has_history) {
5292 print $cgi->a({-href => href(action=>"history",
5293 file_name=>$diff->{'to_file'},
5294 hash_base=>$hash)},
5295 "history");
5297 print "</td>\n";
5299 print "</tr>\n";
5300 next; # instead of 'else' clause, to avoid extra indent
5302 # else ordinary diff
5304 my ($to_mode_oct, $to_mode_str, $to_file_type);
5305 my ($from_mode_oct, $from_mode_str, $from_file_type);
5306 if ($diff->{'to_mode'} ne ('0' x 6)) {
5307 $to_mode_oct = oct $diff->{'to_mode'};
5308 if (S_ISREG($to_mode_oct)) { # only for regular file
5309 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
5311 $to_file_type = file_type($diff->{'to_mode'});
5313 if ($diff->{'from_mode'} ne ('0' x 6)) {
5314 $from_mode_oct = oct $diff->{'from_mode'};
5315 if (S_ISREG($from_mode_oct)) { # only for regular file
5316 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
5318 $from_file_type = file_type($diff->{'from_mode'});
5321 if ($diff->{'status'} eq "A") { # created
5322 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
5323 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
5324 $mode_chng .= "]</span>";
5325 print "<td>";
5326 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5327 hash_base=>$hash, file_name=>$diff->{'file'}),
5328 -class => "list"}, esc_path($diff->{'file'}));
5329 print "</td>\n";
5330 print "<td>$mode_chng</td>\n";
5331 print "<td class=\"link\">";
5332 if ($action eq 'commitdiff') {
5333 # link to patch
5334 $patchno++;
5335 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5336 "patch") .
5337 " | ";
5339 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5340 hash_base=>$hash, file_name=>$diff->{'file'})},
5341 "blob");
5342 print "</td>\n";
5344 } elsif ($diff->{'status'} eq "D") { # deleted
5345 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
5346 print "<td>";
5347 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5348 hash_base=>$parent, file_name=>$diff->{'file'}),
5349 -class => "list"}, esc_path($diff->{'file'}));
5350 print "</td>\n";
5351 print "<td>$mode_chng</td>\n";
5352 print "<td class=\"link\">";
5353 if ($action eq 'commitdiff') {
5354 # link to patch
5355 $patchno++;
5356 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5357 "patch") .
5358 " | ";
5360 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5361 hash_base=>$parent, file_name=>$diff->{'file'})},
5362 "blob") . " | ";
5363 if ($have_blame) {
5364 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
5365 file_name=>$diff->{'file'})},
5366 "blame") . " | ";
5368 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
5369 file_name=>$diff->{'file'})},
5370 "history");
5371 print "</td>\n";
5373 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
5374 my $mode_chnge = "";
5375 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5376 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
5377 if ($from_file_type ne $to_file_type) {
5378 $mode_chnge .= " from $from_file_type to $to_file_type";
5380 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
5381 if ($from_mode_str && $to_mode_str) {
5382 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
5383 } elsif ($to_mode_str) {
5384 $mode_chnge .= " mode: $to_mode_str";
5387 $mode_chnge .= "]</span>\n";
5389 print "<td>";
5390 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5391 hash_base=>$hash, file_name=>$diff->{'file'}),
5392 -class => "list"}, esc_path($diff->{'file'}));
5393 print "</td>\n";
5394 print "<td>$mode_chnge</td>\n";
5395 print "<td class=\"link\">";
5396 if ($action eq 'commitdiff') {
5397 # link to patch
5398 $patchno++;
5399 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5400 "patch") .
5401 " | ";
5402 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5403 # "commit" view and modified file (not onlu mode changed)
5404 print $cgi->a({-href => href(action=>"blobdiff",
5405 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5406 hash_base=>$hash, hash_parent_base=>$parent,
5407 file_name=>$diff->{'file'})},
5408 "diff") .
5409 " | ";
5411 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5412 hash_base=>$hash, file_name=>$diff->{'file'})},
5413 "blob") . " | ";
5414 if ($have_blame) {
5415 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5416 file_name=>$diff->{'file'})},
5417 "blame") . " | ";
5419 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5420 file_name=>$diff->{'file'})},
5421 "history");
5422 print "</td>\n";
5424 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
5425 my %status_name = ('R' => 'moved', 'C' => 'copied');
5426 my $nstatus = $status_name{$diff->{'status'}};
5427 my $mode_chng = "";
5428 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5429 # mode also for directories, so we cannot use $to_mode_str
5430 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
5432 print "<td>" .
5433 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
5434 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
5435 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
5436 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
5437 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
5438 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
5439 -class => "list"}, esc_path($diff->{'from_file'})) .
5440 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
5441 "<td class=\"link\">";
5442 if ($action eq 'commitdiff') {
5443 # link to patch
5444 $patchno++;
5445 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5446 "patch") .
5447 " | ";
5448 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5449 # "commit" view and modified file (not only pure rename or copy)
5450 print $cgi->a({-href => href(action=>"blobdiff",
5451 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5452 hash_base=>$hash, hash_parent_base=>$parent,
5453 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
5454 "diff") .
5455 " | ";
5457 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5458 hash_base=>$parent, file_name=>$diff->{'to_file'})},
5459 "blob") . " | ";
5460 if ($have_blame) {
5461 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5462 file_name=>$diff->{'to_file'})},
5463 "blame") . " | ";
5465 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
5466 file_name=>$diff->{'to_file'})},
5467 "history");
5468 print "</td>\n";
5470 } # we should not encounter Unmerged (U) or Unknown (X) status
5471 print "</tr>\n";
5473 print "</tbody>" if $has_header;
5474 print "</table>\n";
5477 # Print context lines and then rem/add lines in a side-by-side manner.
5478 sub print_sidebyside_diff_lines {
5479 my ($ctx, $rem, $add) = @_;
5481 # print context block before add/rem block
5482 if (@$ctx) {
5483 print join '',
5484 '<div class="chunk_block ctx">',
5485 '<div class="old">',
5486 @$ctx,
5487 '</div>',
5488 '<div class="new">',
5489 @$ctx,
5490 '</div>',
5491 '</div>';
5494 if (!@$add) {
5495 # pure removal
5496 print join '',
5497 '<div class="chunk_block rem">',
5498 '<div class="old">',
5499 @$rem,
5500 '</div>',
5501 '</div>';
5502 } elsif (!@$rem) {
5503 # pure addition
5504 print join '',
5505 '<div class="chunk_block add">',
5506 '<div class="new">',
5507 @$add,
5508 '</div>',
5509 '</div>';
5510 } else {
5511 print join '',
5512 '<div class="chunk_block chg">',
5513 '<div class="old">',
5514 @$rem,
5515 '</div>',
5516 '<div class="new">',
5517 @$add,
5518 '</div>',
5519 '</div>';
5523 # Print context lines and then rem/add lines in inline manner.
5524 sub print_inline_diff_lines {
5525 my ($ctx, $rem, $add) = @_;
5527 print @$ctx, @$rem, @$add;
5530 # Format removed and added line, mark changed part and HTML-format them.
5531 # Implementation is based on contrib/diff-highlight
5532 sub format_rem_add_lines_pair {
5533 my ($rem, $add, $num_parents) = @_;
5535 # We need to untabify lines before split()'ing them;
5536 # otherwise offsets would be invalid.
5537 chomp $rem;
5538 chomp $add;
5539 $rem = untabify($rem);
5540 $add = untabify($add);
5542 my @rem = split(//, $rem);
5543 my @add = split(//, $add);
5544 my ($esc_rem, $esc_add);
5545 # Ignore leading +/- characters for each parent.
5546 my ($prefix_len, $suffix_len) = ($num_parents, 0);
5547 my ($prefix_has_nonspace, $suffix_has_nonspace);
5549 my $shorter = (@rem < @add) ? @rem : @add;
5550 while ($prefix_len < $shorter) {
5551 last if ($rem[$prefix_len] ne $add[$prefix_len]);
5553 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
5554 $prefix_len++;
5557 while ($prefix_len + $suffix_len < $shorter) {
5558 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
5560 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
5561 $suffix_len++;
5564 # Mark lines that are different from each other, but have some common
5565 # part that isn't whitespace. If lines are completely different, don't
5566 # mark them because that would make output unreadable, especially if
5567 # diff consists of multiple lines.
5568 if ($prefix_has_nonspace || $suffix_has_nonspace) {
5569 $esc_rem = esc_html_hl_regions($rem, 'marked',
5570 [$prefix_len, @rem - $suffix_len], -nbsp=>1);
5571 $esc_add = esc_html_hl_regions($add, 'marked',
5572 [$prefix_len, @add - $suffix_len], -nbsp=>1);
5573 } else {
5574 $esc_rem = esc_html($rem, -nbsp=>1);
5575 $esc_add = esc_html($add, -nbsp=>1);
5578 return format_diff_line(\$esc_rem, 'rem'),
5579 format_diff_line(\$esc_add, 'add');
5582 # HTML-format diff context, removed and added lines.
5583 sub format_ctx_rem_add_lines {
5584 my ($ctx, $rem, $add, $num_parents) = @_;
5585 my (@new_ctx, @new_rem, @new_add);
5586 my $can_highlight = 0;
5587 my $is_combined = ($num_parents > 1);
5589 # Highlight if every removed line has a corresponding added line.
5590 if (@$add > 0 && @$add == @$rem) {
5591 $can_highlight = 1;
5593 # Highlight lines in combined diff only if the chunk contains
5594 # diff between the same version, e.g.
5596 # - a
5597 # - b
5598 # + c
5599 # + d
5601 # Otherwise the highlightling would be confusing.
5602 if ($is_combined) {
5603 for (my $i = 0; $i < @$add; $i++) {
5604 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
5605 my $prefix_add = substr($add->[$i], 0, $num_parents);
5607 $prefix_rem =~ s/-/+/g;
5609 if ($prefix_rem ne $prefix_add) {
5610 $can_highlight = 0;
5611 last;
5617 if ($can_highlight) {
5618 for (my $i = 0; $i < @$add; $i++) {
5619 my ($line_rem, $line_add) = format_rem_add_lines_pair(
5620 $rem->[$i], $add->[$i], $num_parents);
5621 push @new_rem, $line_rem;
5622 push @new_add, $line_add;
5624 } else {
5625 @new_rem = map { format_diff_line($_, 'rem') } @$rem;
5626 @new_add = map { format_diff_line($_, 'add') } @$add;
5629 @new_ctx = map { format_diff_line($_, 'ctx') } @$ctx;
5631 return (\@new_ctx, \@new_rem, \@new_add);
5634 # Print context lines and then rem/add lines.
5635 sub print_diff_lines {
5636 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
5637 my $is_combined = $num_parents > 1;
5639 ($ctx, $rem, $add) = format_ctx_rem_add_lines($ctx, $rem, $add,
5640 $num_parents);
5642 if ($diff_style eq 'sidebyside' && !$is_combined) {
5643 print_sidebyside_diff_lines($ctx, $rem, $add);
5644 } else {
5645 # default 'inline' style and unknown styles
5646 print_inline_diff_lines($ctx, $rem, $add);
5650 sub print_diff_chunk {
5651 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
5652 my (@ctx, @rem, @add);
5654 # The class of the previous line.
5655 my $prev_class = '';
5657 return unless @chunk;
5659 # incomplete last line might be among removed or added lines,
5660 # or both, or among context lines: find which
5661 for (my $i = 1; $i < @chunk; $i++) {
5662 if ($chunk[$i][0] eq 'incomplete') {
5663 $chunk[$i][0] = $chunk[$i-1][0];
5667 # guardian
5668 push @chunk, ["", ""];
5670 foreach my $line_info (@chunk) {
5671 my ($class, $line) = @$line_info;
5673 # print chunk headers
5674 if ($class && $class eq 'chunk_header') {
5675 print format_diff_line($line, $class, $from, $to);
5676 next;
5679 ## print from accumulator when have some add/rem lines or end
5680 # of chunk (flush context lines), or when have add and rem
5681 # lines and new block is reached (otherwise add/rem lines could
5682 # be reordered)
5683 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
5684 (@rem && @add && $class ne $prev_class)) {
5685 print_diff_lines(\@ctx, \@rem, \@add,
5686 $diff_style, $num_parents);
5687 @ctx = @rem = @add = ();
5690 ## adding lines to accumulator
5691 # guardian value
5692 last unless $line;
5693 # rem, add or change
5694 if ($class eq 'rem') {
5695 push @rem, $line;
5696 } elsif ($class eq 'add') {
5697 push @add, $line;
5699 # context line
5700 if ($class eq 'ctx') {
5701 push @ctx, $line;
5704 $prev_class = $class;
5708 sub git_patchset_body {
5709 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
5710 my ($hash_parent) = $hash_parents[0];
5712 my $is_combined = (@hash_parents > 1);
5713 my $patch_idx = 0;
5714 my $patch_number = 0;
5715 my $patch_line;
5716 my $diffinfo;
5717 my $to_name;
5718 my (%from, %to);
5719 my @chunk; # for side-by-side diff
5721 print "<div class=\"patchset\">\n";
5723 # skip to first patch
5724 while ($patch_line = to_utf8(scalar <$fd>)) {
5725 chomp $patch_line;
5727 last if ($patch_line =~ m/^diff /);
5730 PATCH:
5731 while ($patch_line) {
5733 # parse "git diff" header line
5734 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
5735 # $1 is from_name, which we do not use
5736 $to_name = unquote($2);
5737 $to_name =~ s!^b/!!;
5738 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
5739 # $1 is 'cc' or 'combined', which we do not use
5740 $to_name = unquote($2);
5741 } else {
5742 $to_name = undef;
5745 # check if current patch belong to current raw line
5746 # and parse raw git-diff line if needed
5747 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
5748 # this is continuation of a split patch
5749 print "<div class=\"patch cont\">\n";
5750 } else {
5751 # advance raw git-diff output if needed
5752 $patch_idx++ if defined $diffinfo;
5754 # read and prepare patch information
5755 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5757 # compact combined diff output can have some patches skipped
5758 # find which patch (using pathname of result) we are at now;
5759 if ($is_combined) {
5760 while ($to_name ne $diffinfo->{'to_file'}) {
5761 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5762 format_diff_cc_simplified($diffinfo, @hash_parents) .
5763 "</div>\n"; # class="patch"
5765 $patch_idx++;
5766 $patch_number++;
5768 last if $patch_idx > $#$difftree;
5769 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5773 # modifies %from, %to hashes
5774 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
5776 # this is first patch for raw difftree line with $patch_idx index
5777 # we index @$difftree array from 0, but number patches from 1
5778 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
5781 # git diff header
5782 #assert($patch_line =~ m/^diff /) if DEBUG;
5783 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
5784 $patch_number++;
5785 # print "git diff" header
5786 print format_git_diff_header_line($patch_line, $diffinfo,
5787 \%from, \%to);
5789 # print extended diff header
5790 print "<div class=\"diff extended_header\">\n";
5791 EXTENDED_HEADER:
5792 while ($patch_line = to_utf8(scalar<$fd>)) {
5793 chomp $patch_line;
5795 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
5797 print format_extended_diff_header_line($patch_line, $diffinfo,
5798 \%from, \%to);
5800 print "</div>\n"; # class="diff extended_header"
5802 # from-file/to-file diff header
5803 if (! $patch_line) {
5804 print "</div>\n"; # class="patch"
5805 last PATCH;
5807 next PATCH if ($patch_line =~ m/^diff /);
5808 #assert($patch_line =~ m/^---/) if DEBUG;
5810 my $last_patch_line = $patch_line;
5811 $patch_line = to_utf8(scalar <$fd>);
5812 chomp $patch_line;
5813 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
5815 print format_diff_from_to_header($last_patch_line, $patch_line,
5816 $diffinfo, \%from, \%to,
5817 @hash_parents);
5819 # the patch itself
5820 LINE:
5821 while ($patch_line = to_utf8(scalar <$fd>)) {
5822 chomp $patch_line;
5824 next PATCH if ($patch_line =~ m/^diff /);
5826 my $class = diff_line_class($patch_line, \%from, \%to);
5828 if ($class eq 'chunk_header') {
5829 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5830 @chunk = ();
5833 push @chunk, [ $class, $patch_line ];
5836 } continue {
5837 if (@chunk) {
5838 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
5839 @chunk = ();
5841 print "</div>\n"; # class="patch"
5844 # for compact combined (--cc) format, with chunk and patch simplification
5845 # the patchset might be empty, but there might be unprocessed raw lines
5846 for (++$patch_idx if $patch_number > 0;
5847 $patch_idx < @$difftree;
5848 ++$patch_idx) {
5849 # read and prepare patch information
5850 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
5852 # generate anchor for "patch" links in difftree / whatchanged part
5853 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
5854 format_diff_cc_simplified($diffinfo, @hash_parents) .
5855 "</div>\n"; # class="patch"
5857 $patch_number++;
5860 if ($patch_number == 0) {
5861 if (@hash_parents > 1) {
5862 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
5863 } else {
5864 print "<div class=\"diff nodifferences\">No differences found</div>\n";
5868 print "</div>\n"; # class="patchset"
5871 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5873 sub git_project_search_form {
5874 my ($searchtext, $search_use_regexp) = @_;
5876 my $limit = '';
5877 if ($project_filter) {
5878 $limit = " in '$project_filter/'";
5881 print "<div class=\"projsearch\">\n";
5882 print $cgi->start_form(-method => 'get', -action => $my_uri) .
5883 $cgi->hidden(-name => 'a', -value => 'project_list') . "\n";
5884 print $cgi->hidden(-name => 'pf', -value => $project_filter). "\n"
5885 if (defined $project_filter);
5886 print $cgi->textfield(-name => 's', -value => $searchtext,
5887 -title => "Search project by name and description$limit",
5888 -size => 60) . "\n" .
5889 "<span title=\"Extended regular expression\">" .
5890 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
5891 -checked => $search_use_regexp) .
5892 "</span>\n" .
5893 $cgi->submit(-name => 'btnS', -value => 'Search') .
5894 $cgi->end_form() . "\n" .
5895 $cgi->a({-href => href(project => undef, searchtext => undef,
5896 project_filter => $project_filter)},
5897 esc_html("List all projects$limit")) . "<br />\n";
5898 print "</div>\n";
5901 # entry for given @keys needs filling if at least one of keys in list
5902 # is not present in %$project_info
5903 sub project_info_needs_filling {
5904 my ($project_info, @keys) = @_;
5906 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
5907 foreach my $key (@keys) {
5908 if (!exists $project_info->{$key}) {
5909 return 1;
5912 return;
5915 # fills project list info (age, description, owner, category, forks, etc.)
5916 # for each project in the list, removing invalid projects from
5917 # returned list, or fill only specified info.
5919 # Invalid projects are removed from the returned list if and only if you
5920 # ask 'age' or 'age_string' to be filled, because they are the only fields
5921 # that run unconditionally git command that requires repository, and
5922 # therefore do always check if project repository is invalid.
5924 # USAGE:
5925 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
5926 # ensures that 'descr_long' and 'ctags' fields are filled
5927 # * @project_list = fill_project_list_info(\@project_list)
5928 # ensures that all fields are filled (and invalid projects removed)
5930 # NOTE: modifies $projlist, but does not remove entries from it
5931 sub fill_project_list_info {
5932 my ($projlist, @wanted_keys) = @_;
5933 my @projects;
5934 my $filter_set = sub { return @_; };
5935 if (@wanted_keys) {
5936 my %wanted_keys = map { $_ => 1 } @wanted_keys;
5937 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
5940 my $show_ctags = gitweb_check_feature('ctags');
5941 PROJECT:
5942 foreach my $pr (@$projlist) {
5943 if (project_info_needs_filling($pr, $filter_set->('age', 'age_string'))) {
5944 my (@activity) = git_get_last_activity($pr->{'path'});
5945 unless (@activity) {
5946 next PROJECT;
5948 ($pr->{'age'}, $pr->{'age_string'}) = @activity;
5950 if (project_info_needs_filling($pr, $filter_set->('descr', 'descr_long'))) {
5951 my $descr = git_get_project_description($pr->{'path'}) || "";
5952 $descr = to_utf8($descr);
5953 $pr->{'descr_long'} = $descr;
5954 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
5956 if (project_info_needs_filling($pr, $filter_set->('owner'))) {
5957 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
5959 if ($show_ctags &&
5960 project_info_needs_filling($pr, $filter_set->('ctags'))) {
5961 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
5963 if ($projects_list_group_categories &&
5964 project_info_needs_filling($pr, $filter_set->('category'))) {
5965 my $cat = git_get_project_category($pr->{'path'}) ||
5966 $project_list_default_category;
5967 $pr->{'category'} = to_utf8($cat);
5970 push @projects, $pr;
5973 return @projects;
5976 sub sort_projects_list {
5977 my ($projlist, $order) = @_;
5979 sub order_str {
5980 my $key = shift;
5981 return sub { $a->{$key} cmp $b->{$key} };
5984 sub order_num_then_undef {
5985 my $key = shift;
5986 return sub {
5987 defined $a->{$key} ?
5988 (defined $b->{$key} ? $a->{$key} <=> $b->{$key} : -1) :
5989 (defined $b->{$key} ? 1 : 0)
5993 my %orderings = (
5994 project => order_str('path'),
5995 descr => order_str('descr_long'),
5996 owner => order_str('owner'),
5997 age => order_num_then_undef('age'),
6000 my $ordering = $orderings{$order};
6001 return defined $ordering ? sort $ordering @$projlist : @$projlist;
6004 # returns a hash of categories, containing the list of project
6005 # belonging to each category
6006 sub build_projlist_by_category {
6007 my ($projlist, $from, $to) = @_;
6008 my %categories;
6010 $from = 0 unless defined $from;
6011 $to = $#$projlist if (!defined $to || $#$projlist < $to);
6013 for (my $i = $from; $i <= $to; $i++) {
6014 my $pr = $projlist->[$i];
6015 push @{$categories{ $pr->{'category'} }}, $pr;
6018 return wantarray ? %categories : \%categories;
6021 # print 'sort by' <th> element, generating 'sort by $name' replay link
6022 # if that order is not selected
6023 sub print_sort_th {
6024 print format_sort_th(@_);
6027 sub format_sort_th {
6028 my ($name, $order, $header) = @_;
6029 my $sort_th = "";
6030 $header ||= ucfirst($name);
6032 if ($order eq $name) {
6033 $sort_th .= "<th>$header</th>\n";
6034 } else {
6035 $sort_th .= "<th>" .
6036 $cgi->a({-href => href(-replay=>1, order=>$name),
6037 -class => "header"}, $header) .
6038 "</th>\n";
6041 return $sort_th;
6044 sub git_project_list_rows {
6045 my ($projlist, $from, $to, $check_forks) = @_;
6047 $from = 0 unless defined $from;
6048 $to = $#$projlist if (!defined $to || $#$projlist < $to);
6050 my $alternate = 1;
6051 for (my $i = $from; $i <= $to; $i++) {
6052 my $pr = $projlist->[$i];
6054 if ($alternate) {
6055 print "<tr class=\"dark\">\n";
6056 } else {
6057 print "<tr class=\"light\">\n";
6059 $alternate ^= 1;
6061 if ($check_forks) {
6062 print "<td>";
6063 if ($pr->{'forks'}) {
6064 my $nforks = scalar @{$pr->{'forks'}};
6065 if ($nforks > 0) {
6066 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
6067 -title => "$nforks forks"}, "+");
6068 } else {
6069 print $cgi->span({-title => "$nforks forks"}, "+");
6072 print "</td>\n";
6074 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
6075 -class => "list"},
6076 esc_html_match_hl($pr->{'path'}, $search_regexp)) .
6077 "</td>\n" .
6078 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
6079 -class => "list",
6080 -title => $pr->{'descr_long'}},
6081 $search_regexp
6082 ? esc_html_match_hl_chopped($pr->{'descr_long'},
6083 $pr->{'descr'}, $search_regexp)
6084 : esc_html($pr->{'descr'})) .
6085 "</td>\n";
6086 unless ($omit_owner) {
6087 print "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
6089 unless ($omit_age_column) {
6090 print "<td class=\"". age_class($pr->{'age'}) . "\">" .
6091 (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n";
6093 print"<td class=\"link\">" .
6094 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
6095 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "shortlog") . " | " .
6096 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"log")}, "log") . " | " .
6097 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
6098 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
6099 "</td>\n" .
6100 "</tr>\n";
6104 sub git_project_list_body {
6105 # actually uses global variable $project
6106 my ($projlist, $order, $from, $to, $extra, $no_header) = @_;
6107 my @projects = @$projlist;
6109 my $check_forks = gitweb_check_feature('forks');
6110 my $show_ctags = gitweb_check_feature('ctags');
6111 my $tagfilter = $show_ctags ? $input_params{'ctag'} : undef;
6112 $check_forks = undef
6113 if ($tagfilter || $search_regexp);
6115 # filtering out forks before filling info allows to do less work
6116 @projects = filter_forks_from_projects_list(\@projects)
6117 if ($check_forks);
6118 # search_projects_list pre-fills required info
6119 @projects = search_projects_list(\@projects,
6120 'search_regexp' => $search_regexp,
6121 'tagfilter' => $tagfilter)
6122 if ($tagfilter || $search_regexp);
6123 # fill the rest
6124 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
6125 push @all_fields, ('age', 'age_string') unless($omit_age_column);
6126 push @all_fields, 'owner' unless($omit_owner);
6127 @projects = fill_project_list_info(\@projects, @all_fields);
6129 $order ||= $default_projects_order;
6130 $from = 0 unless defined $from;
6131 $to = $#projects if (!defined $to || $#projects < $to);
6133 # short circuit
6134 if ($from > $to) {
6135 print "<center>\n".
6136 "<b>No such projects found</b><br />\n".
6137 "Click ".$cgi->a({-href=>href(project=>undef)},"here")." to view all projects<br />\n".
6138 "</center>\n<br />\n";
6139 return;
6142 @projects = sort_projects_list(\@projects, $order);
6144 if ($show_ctags) {
6145 my $ctags = git_gather_all_ctags(\@projects);
6146 my $cloud = git_populate_project_tagcloud($ctags);
6147 print git_show_project_tagcloud($cloud, 64);
6150 print "<table class=\"project_list\">\n";
6151 unless ($no_header) {
6152 print "<tr>\n";
6153 if ($check_forks) {
6154 print "<th></th>\n";
6156 print_sort_th('project', $order, 'Project');
6157 print_sort_th('descr', $order, 'Description');
6158 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
6159 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
6160 print "<th></th>\n" . # for links
6161 "</tr>\n";
6164 if ($projects_list_group_categories) {
6165 # only display categories with projects in the $from-$to window
6166 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
6167 my %categories = build_projlist_by_category(\@projects, $from, $to);
6168 foreach my $cat (sort keys %categories) {
6169 unless ($cat eq "") {
6170 print "<tr>\n";
6171 if ($check_forks) {
6172 print "<td></td>\n";
6174 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
6175 print "</tr>\n";
6178 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
6180 } else {
6181 git_project_list_rows(\@projects, $from, $to, $check_forks);
6184 if (defined $extra) {
6185 print "<tr>\n";
6186 if ($check_forks) {
6187 print "<td></td>\n";
6189 print "<td colspan=\"5\">$extra</td>\n" .
6190 "</tr>\n";
6192 print "</table>\n";
6195 sub git_log_body {
6196 # uses global variable $project
6197 my ($commitlist, $from, $to, $refs, $extra) = @_;
6199 $from = 0 unless defined $from;
6200 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6202 for (my $i = 0; $i <= $to; $i++) {
6203 my %co = %{$commitlist->[$i]};
6204 next if !%co;
6205 my $commit = $co{'id'};
6206 my $ref = format_ref_marker($refs, $commit);
6207 git_print_header_div('commit',
6208 "<span class=\"age\">$co{'age_string'}</span>" .
6209 esc_html($co{'title'}) . $ref,
6210 $commit);
6211 print "<div class=\"title_text\">\n" .
6212 "<div class=\"log_link\">\n" .
6213 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
6214 " | " .
6215 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
6216 " | " .
6217 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
6218 "<br/>\n" .
6219 "</div>\n";
6220 git_print_authorship(\%co, -tag => 'span');
6221 print "<br/>\n</div>\n";
6223 print "<div class=\"log_body\">\n";
6224 git_print_log($co{'comment'}, -final_empty_line=> 1);
6225 print "</div>\n";
6227 if ($extra) {
6228 print "<div class=\"page_nav\">\n";
6229 print "$extra\n";
6230 print "</div>\n";
6234 sub git_shortlog_body {
6235 # uses global variable $project
6236 my ($commitlist, $from, $to, $refs, $extra) = @_;
6238 $from = 0 unless defined $from;
6239 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6241 print "<table class=\"shortlog\">\n";
6242 my $alternate = 1;
6243 for (my $i = $from; $i <= $to; $i++) {
6244 my %co = %{$commitlist->[$i]};
6245 my $commit = $co{'id'};
6246 my $ref = format_ref_marker($refs, $commit);
6247 if ($alternate) {
6248 print "<tr class=\"dark\">\n";
6249 } else {
6250 print "<tr class=\"light\">\n";
6252 $alternate ^= 1;
6253 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
6254 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6255 format_author_html('td', \%co, 10) . "<td>";
6256 print format_subject_html($co{'title'}, $co{'title_short'},
6257 href(action=>"commit", hash=>$commit), $ref);
6258 print "</td>\n" .
6259 "<td class=\"link\">" .
6260 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
6261 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
6262 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
6263 my $snapshot_links = format_snapshot_links($commit);
6264 if (defined $snapshot_links) {
6265 print " | " . $snapshot_links;
6267 print "</td>\n" .
6268 "</tr>\n";
6270 if (defined $extra) {
6271 print "<tr>\n" .
6272 "<td colspan=\"4\">$extra</td>\n" .
6273 "</tr>\n";
6275 print "</table>\n";
6278 sub git_history_body {
6279 # Warning: assumes constant type (blob or tree) during history
6280 my ($commitlist, $from, $to, $refs, $extra,
6281 $file_name, $file_hash, $ftype) = @_;
6283 $from = 0 unless defined $from;
6284 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
6286 print "<table class=\"history\">\n";
6287 my $alternate = 1;
6288 for (my $i = $from; $i <= $to; $i++) {
6289 my %co = %{$commitlist->[$i]};
6290 if (!%co) {
6291 next;
6293 my $commit = $co{'id'};
6295 my $ref = format_ref_marker($refs, $commit);
6297 if ($alternate) {
6298 print "<tr class=\"dark\">\n";
6299 } else {
6300 print "<tr class=\"light\">\n";
6302 $alternate ^= 1;
6303 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6304 # shortlog: format_author_html('td', \%co, 10)
6305 format_author_html('td', \%co, 15, 3) . "<td>";
6306 # originally git_history used chop_str($co{'title'}, 50)
6307 print format_subject_html($co{'title'}, $co{'title_short'},
6308 href(action=>"commit", hash=>$commit), $ref);
6309 print "</td>\n" .
6310 "<td class=\"link\">" .
6311 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
6312 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
6314 if ($ftype eq 'blob') {
6315 my $blob_current = $file_hash;
6316 my $blob_parent = git_get_hash_by_path($commit, $file_name);
6317 if (defined $blob_current && defined $blob_parent &&
6318 $blob_current ne $blob_parent) {
6319 print " | " .
6320 $cgi->a({-href => href(action=>"blobdiff",
6321 hash=>$blob_current, hash_parent=>$blob_parent,
6322 hash_base=>$hash_base, hash_parent_base=>$commit,
6323 file_name=>$file_name)},
6324 "diff to current");
6327 print "</td>\n" .
6328 "</tr>\n";
6330 if (defined $extra) {
6331 print "<tr>\n" .
6332 "<td colspan=\"4\">$extra</td>\n" .
6333 "</tr>\n";
6335 print "</table>\n";
6338 sub git_tags_body {
6339 # uses global variable $project
6340 my ($taglist, $from, $to, $extra) = @_;
6341 $from = 0 unless defined $from;
6342 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
6344 print "<table class=\"tags\">\n";
6345 my $alternate = 1;
6346 for (my $i = $from; $i <= $to; $i++) {
6347 my $entry = $taglist->[$i];
6348 my %tag = %$entry;
6349 my $comment = $tag{'subject'};
6350 my $comment_short;
6351 if (defined $comment) {
6352 $comment_short = chop_str($comment, 30, 5);
6354 if ($alternate) {
6355 print "<tr class=\"dark\">\n";
6356 } else {
6357 print "<tr class=\"light\">\n";
6359 $alternate ^= 1;
6360 if (defined $tag{'age'}) {
6361 print "<td><i>$tag{'age'}</i></td>\n";
6362 } else {
6363 print "<td></td>\n";
6365 print "<td>" .
6366 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
6367 -class => "list name"}, esc_html($tag{'name'})) .
6368 "</td>\n" .
6369 "<td>";
6370 if (defined $comment) {
6371 print format_subject_html($comment, $comment_short,
6372 href(action=>"tag", hash=>$tag{'id'}));
6374 print "</td>\n" .
6375 "<td class=\"selflink\">";
6376 if ($tag{'type'} eq "tag") {
6377 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
6378 } else {
6379 print "&nbsp;";
6381 print "</td>\n" .
6382 "<td class=\"link\">" . " | " .
6383 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
6384 if ($tag{'reftype'} eq "commit") {
6385 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
6386 " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
6387 } elsif ($tag{'reftype'} eq "blob") {
6388 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
6390 print "</td>\n" .
6391 "</tr>";
6393 if (defined $extra) {
6394 print "<tr>\n" .
6395 "<td colspan=\"5\">$extra</td>\n" .
6396 "</tr>\n";
6398 print "</table>\n";
6401 sub git_heads_body {
6402 # uses global variable $project
6403 my ($headlist, $head_at, $from, $to, $extra) = @_;
6404 $from = 0 unless defined $from;
6405 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
6407 print "<table class=\"heads\">\n";
6408 my $alternate = 1;
6409 for (my $i = $from; $i <= $to; $i++) {
6410 my $entry = $headlist->[$i];
6411 my %ref = %$entry;
6412 my $curr = defined $head_at && $ref{'id'} eq $head_at;
6413 if ($alternate) {
6414 print "<tr class=\"dark\">\n";
6415 } else {
6416 print "<tr class=\"light\">\n";
6418 $alternate ^= 1;
6419 print "<td><i>$ref{'age'}</i></td>\n" .
6420 ($curr ? "<td class=\"current_head\">" : "<td>") .
6421 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
6422 -class => "list name"},esc_html($ref{'name'})) .
6423 "</td>\n" .
6424 "<td class=\"link\">" .
6425 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
6426 $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
6427 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
6428 "</td>\n" .
6429 "</tr>";
6431 if (defined $extra) {
6432 print "<tr>\n" .
6433 "<td colspan=\"3\">$extra</td>\n" .
6434 "</tr>\n";
6436 print "</table>\n";
6439 # Display a single remote block
6440 sub git_remote_block {
6441 my ($remote, $rdata, $limit, $head) = @_;
6443 my $heads = $rdata->{'heads'};
6444 my $fetch = $rdata->{'fetch'};
6445 my $push = $rdata->{'push'};
6447 my $urls_table = "<table class=\"projects_list\">\n" ;
6449 if (defined $fetch) {
6450 if ($fetch eq $push) {
6451 $urls_table .= format_repo_url("URL", $fetch);
6452 } else {
6453 $urls_table .= format_repo_url("Fetch URL", $fetch);
6454 $urls_table .= format_repo_url("Push URL", $push) if defined $push;
6456 } elsif (defined $push) {
6457 $urls_table .= format_repo_url("Push URL", $push);
6458 } else {
6459 $urls_table .= format_repo_url("", "No remote URL");
6462 $urls_table .= "</table>\n";
6464 my $dots;
6465 if (defined $limit && $limit < @$heads) {
6466 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
6469 print $urls_table;
6470 git_heads_body($heads, $head, 0, $limit, $dots);
6473 # Display a list of remote names with the respective fetch and push URLs
6474 sub git_remotes_list {
6475 my ($remotedata, $limit) = @_;
6476 print "<table class=\"heads\">\n";
6477 my $alternate = 1;
6478 my @remotes = sort keys %$remotedata;
6480 my $limited = $limit && $limit < @remotes;
6482 $#remotes = $limit - 1 if $limited;
6484 while (my $remote = shift @remotes) {
6485 my $rdata = $remotedata->{$remote};
6486 my $fetch = $rdata->{'fetch'};
6487 my $push = $rdata->{'push'};
6488 if ($alternate) {
6489 print "<tr class=\"dark\">\n";
6490 } else {
6491 print "<tr class=\"light\">\n";
6493 $alternate ^= 1;
6494 print "<td>" .
6495 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
6496 -class=> "list name"},esc_html($remote)) .
6497 "</td>";
6498 print "<td class=\"link\">" .
6499 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
6500 " | " .
6501 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
6502 "</td>";
6504 print "</tr>\n";
6507 if ($limited) {
6508 print "<tr>\n" .
6509 "<td colspan=\"3\">" .
6510 $cgi->a({-href => href(action=>"remotes")}, "...") .
6511 "</td>\n" . "</tr>\n";
6514 print "</table>";
6517 # Display remote heads grouped by remote, unless there are too many
6518 # remotes, in which case we only display the remote names
6519 sub git_remotes_body {
6520 my ($remotedata, $limit, $head) = @_;
6521 if ($limit and $limit < keys %$remotedata) {
6522 git_remotes_list($remotedata, $limit);
6523 } else {
6524 fill_remote_heads($remotedata);
6525 while (my ($remote, $rdata) = each %$remotedata) {
6526 git_print_section({-class=>"remote", -id=>$remote},
6527 ["remotes", $remote, $remote], sub {
6528 git_remote_block($remote, $rdata, $limit, $head);
6534 sub git_search_message {
6535 my %co = @_;
6537 my $greptype;
6538 if ($searchtype eq 'commit') {
6539 $greptype = "--grep=";
6540 } elsif ($searchtype eq 'author') {
6541 $greptype = "--author=";
6542 } elsif ($searchtype eq 'committer') {
6543 $greptype = "--committer=";
6545 $greptype .= $searchtext;
6546 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
6547 $greptype, '--regexp-ignore-case',
6548 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
6550 my $paging_nav = '';
6551 if ($page > 0) {
6552 $paging_nav .=
6553 $cgi->a({-href => href(-replay=>1, page=>undef)},
6554 "first") .
6555 " &sdot; " .
6556 $cgi->a({-href => href(-replay=>1, page=>$page-1),
6557 -accesskey => "p", -title => "Alt-p"}, "prev");
6558 } else {
6559 $paging_nav .= "first &sdot; prev";
6561 my $next_link = '';
6562 if ($#commitlist >= 100) {
6563 $next_link =
6564 $cgi->a({-href => href(-replay=>1, page=>$page+1),
6565 -accesskey => "n", -title => "Alt-n"}, "next");
6566 $paging_nav .= " &sdot; $next_link";
6567 } else {
6568 $paging_nav .= " &sdot; next";
6571 git_header_html();
6573 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
6574 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6575 if ($page == 0 && !@commitlist) {
6576 print "<p>No match.</p>\n";
6577 } else {
6578 git_search_grep_body(\@commitlist, 0, 99, $next_link);
6581 git_footer_html();
6584 sub git_search_changes {
6585 my %co = @_;
6587 local $/ = "\n";
6588 defined(my $fd = git_cmd_pipe '--no-pager', 'log', @diff_opts,
6589 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
6590 ($search_use_regexp ? '--pickaxe-regex' : ()))
6591 or die_error(500, "Open git-log failed");
6593 git_header_html();
6595 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6596 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6598 print "<table class=\"pickaxe search\">\n";
6599 my $alternate = 1;
6600 undef %co;
6601 my @files;
6602 while (my $line = to_utf8(scalar <$fd>)) {
6603 chomp $line;
6604 next unless $line;
6606 my %set = parse_difftree_raw_line($line);
6607 if (defined $set{'commit'}) {
6608 # finish previous commit
6609 if (%co) {
6610 print "</td>\n" .
6611 "<td class=\"link\">" .
6612 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6613 "commit") .
6614 " | " .
6615 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6616 hash_base=>$co{'id'})},
6617 "tree") .
6618 "</td>\n" .
6619 "</tr>\n";
6622 if ($alternate) {
6623 print "<tr class=\"dark\">\n";
6624 } else {
6625 print "<tr class=\"light\">\n";
6627 $alternate ^= 1;
6628 %co = parse_commit($set{'commit'});
6629 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
6630 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6631 "<td><i>$author</i></td>\n" .
6632 "<td>" .
6633 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6634 -class => "list subject"},
6635 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6636 } elsif (defined $set{'to_id'}) {
6637 next if ($set{'to_id'} =~ m/^0{40}$/);
6639 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
6640 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
6641 -class => "list"},
6642 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
6643 "<br/>\n";
6646 close $fd;
6648 # finish last commit (warning: repetition!)
6649 if (%co) {
6650 print "</td>\n" .
6651 "<td class=\"link\">" .
6652 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
6653 "commit") .
6654 " | " .
6655 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
6656 hash_base=>$co{'id'})},
6657 "tree") .
6658 "</td>\n" .
6659 "</tr>\n";
6662 print "</table>\n";
6664 git_footer_html();
6667 sub git_search_files {
6668 my %co = @_;
6670 local $/ = "\n";
6671 defined(my $fd = git_cmd_pipe 'grep', '-n', '-z',
6672 $search_use_regexp ? ('-E', '-i') : '-F',
6673 $searchtext, $co{'tree'})
6674 or die_error(500, "Open git-grep failed");
6676 git_header_html();
6678 git_print_page_nav('','', $hash,$co{'tree'},$hash);
6679 git_print_header_div('commit', esc_html($co{'title'}), $hash);
6681 print "<table class=\"grep_search\">\n";
6682 my $alternate = 1;
6683 my $matches = 0;
6684 my $lastfile = '';
6685 my $file_href;
6686 while (my $line = to_utf8(scalar <$fd>)) {
6687 chomp $line;
6688 my ($file, $lno, $ltext, $binary);
6689 last if ($matches++ > 1000);
6690 if ($line =~ /^Binary file (.+) matches$/) {
6691 $file = $1;
6692 $binary = 1;
6693 } else {
6694 ($file, $lno, $ltext) = split(/\0/, $line, 3);
6695 $file =~ s/^$co{'tree'}://;
6697 if ($file ne $lastfile) {
6698 $lastfile and print "</td></tr>\n";
6699 if ($alternate++) {
6700 print "<tr class=\"dark\">\n";
6701 } else {
6702 print "<tr class=\"light\">\n";
6704 $file_href = href(action=>"blob", hash_base=>$co{'id'},
6705 file_name=>$file);
6706 print "<td class=\"list\">".
6707 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
6708 print "</td><td>\n";
6709 $lastfile = $file;
6711 if ($binary) {
6712 print "<div class=\"binary\">Binary file</div>\n";
6713 } else {
6714 $ltext = untabify($ltext);
6715 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
6716 $ltext = esc_html($1, -nbsp=>1);
6717 $ltext .= '<span class="match">';
6718 $ltext .= esc_html($2, -nbsp=>1);
6719 $ltext .= '</span>';
6720 $ltext .= esc_html($3, -nbsp=>1);
6721 } else {
6722 $ltext = esc_html($ltext, -nbsp=>1);
6724 print "<div class=\"pre\">" .
6725 $cgi->a({-href => $file_href.'#l'.$lno,
6726 -class => "linenr"}, sprintf('%4i', $lno)) .
6727 ' ' . $ltext . "</div>\n";
6730 if ($lastfile) {
6731 print "</td></tr>\n";
6732 if ($matches > 1000) {
6733 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
6735 } else {
6736 print "<div class=\"diff nodifferences\">No matches found</div>\n";
6738 close $fd;
6740 print "</table>\n";
6742 git_footer_html();
6745 sub git_search_grep_body {
6746 my ($commitlist, $from, $to, $extra) = @_;
6747 $from = 0 unless defined $from;
6748 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6750 print "<table class=\"commit_search\">\n";
6751 my $alternate = 1;
6752 for (my $i = $from; $i <= $to; $i++) {
6753 my %co = %{$commitlist->[$i]};
6754 if (!%co) {
6755 next;
6757 my $commit = $co{'id'};
6758 if ($alternate) {
6759 print "<tr class=\"dark\">\n";
6760 } else {
6761 print "<tr class=\"light\">\n";
6763 $alternate ^= 1;
6764 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
6765 format_author_html('td', \%co, 15, 5) .
6766 "<td>" .
6767 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
6768 -class => "list subject"},
6769 chop_and_escape_str($co{'title'}, 50) . "<br/>");
6770 my $comment = $co{'comment'};
6771 foreach my $line (@$comment) {
6772 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
6773 my ($lead, $match, $trail) = ($1, $2, $3);
6774 $match = chop_str($match, 70, 5, 'center');
6775 my $contextlen = int((80 - length($match))/2);
6776 $contextlen = 30 if ($contextlen > 30);
6777 $lead = chop_str($lead, $contextlen, 10, 'left');
6778 $trail = chop_str($trail, $contextlen, 10, 'right');
6780 $lead = esc_html($lead);
6781 $match = esc_html($match);
6782 $trail = esc_html($trail);
6784 print "$lead<span class=\"match\">$match</span>$trail<br />";
6787 print "</td>\n" .
6788 "<td class=\"link\">" .
6789 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
6790 " | " .
6791 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
6792 " | " .
6793 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
6794 print "</td>\n" .
6795 "</tr>\n";
6797 if (defined $extra) {
6798 print "<tr>\n" .
6799 "<td colspan=\"3\">$extra</td>\n" .
6800 "</tr>\n";
6802 print "</table>\n";
6805 ## ======================================================================
6806 ## ======================================================================
6807 ## actions
6809 sub git_project_list {
6810 my $order = $input_params{'order'};
6811 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6812 die_error(400, "Unknown order parameter");
6815 my @list = git_get_projects_list($project_filter, $strict_export);
6816 if (!@list) {
6817 die_error(404, "No projects found");
6820 git_header_html();
6821 if (defined $home_text && -f $home_text) {
6822 print "<div class=\"index_include\">\n";
6823 insert_file($home_text);
6824 print "</div>\n";
6827 git_project_search_form($searchtext, $search_use_regexp);
6828 git_project_list_body(\@list, $order);
6829 git_footer_html();
6832 sub git_forks {
6833 my $order = $input_params{'order'};
6834 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
6835 die_error(400, "Unknown order parameter");
6838 my $filter = $project;
6839 $filter =~ s/\.git$//;
6840 my @list = git_get_projects_list($filter);
6841 if (!@list) {
6842 die_error(404, "No forks found");
6845 git_header_html();
6846 git_print_page_nav('','');
6847 git_print_header_div('summary', "$project forks");
6848 git_project_list_body(\@list, $order);
6849 git_footer_html();
6852 sub git_project_index {
6853 my @projects = git_get_projects_list($project_filter, $strict_export);
6854 if (!@projects) {
6855 die_error(404, "No projects found");
6858 print $cgi->header(
6859 -type => 'text/plain',
6860 -charset => 'utf-8',
6861 -content_disposition => 'inline; filename="index.aux"');
6863 foreach my $pr (@projects) {
6864 if (!exists $pr->{'owner'}) {
6865 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
6868 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
6869 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
6870 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6871 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
6872 $path =~ s/ /\+/g;
6873 $owner =~ s/ /\+/g;
6875 print "$path $owner\n";
6879 sub git_summary {
6880 my $descr = git_get_project_description($project) || "none";
6881 my %co = parse_commit("HEAD");
6882 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
6883 my $head = $co{'id'};
6884 my $remote_heads = gitweb_check_feature('remote_heads');
6886 my $owner = git_get_project_owner($project);
6888 my $refs = git_get_references();
6889 # These get_*_list functions return one more to allow us to see if
6890 # there are more ...
6891 my @taglist = git_get_tags_list(16);
6892 my @headlist = git_get_heads_list(16);
6893 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
6894 my @forklist;
6895 my $check_forks = gitweb_check_feature('forks');
6897 if ($check_forks) {
6898 # find forks of a project
6899 my $filter = $project;
6900 $filter =~ s/\.git$//;
6901 @forklist = git_get_projects_list($filter);
6902 # filter out forks of forks
6903 @forklist = filter_forks_from_projects_list(\@forklist)
6904 if (@forklist);
6907 git_header_html();
6908 git_print_page_nav('summary','', $head);
6910 print "<div class=\"title\">&nbsp;</div>\n";
6911 print "<table class=\"projects_list\">\n" .
6912 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
6913 if ($owner and not $omit_owner) {
6914 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
6916 if (defined $cd{'rfc2822'}) {
6917 print "<tr id=\"metadata_lchange\"><td>last change</td>" .
6918 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
6921 # use per project git URL list in $projectroot/$project/cloneurl
6922 # or make project git URL from git base URL and project name
6923 my $url_tag = "URL";
6924 my @url_list = git_get_project_url_list($project);
6925 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
6926 foreach my $git_url (@url_list) {
6927 next unless $git_url;
6928 print format_repo_url($url_tag, $git_url);
6929 $url_tag = "";
6932 # Tag cloud
6933 my $show_ctags = gitweb_check_feature('ctags');
6934 if ($show_ctags) {
6935 my $ctags = git_get_project_ctags($project);
6936 if (%$ctags) {
6937 # without ability to add tags, don't show if there are none
6938 my $cloud = git_populate_project_tagcloud($ctags);
6939 print "<tr id=\"metadata_ctags\">" .
6940 "<td>content tags</td>" .
6941 "<td>".git_show_project_tagcloud($cloud, 48)."</td>" .
6942 "</tr>\n";
6946 print "</table>\n";
6948 # If XSS prevention is on, we don't include README.html.
6949 # TODO: Allow a readme in some safe format.
6950 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
6951 print "<div class=\"title\">readme</div>\n" .
6952 "<div class=\"readme\">\n";
6953 insert_file("$projectroot/$project/README.html");
6954 print "\n</div>\n"; # class="readme"
6957 # we need to request one more than 16 (0..15) to check if
6958 # those 16 are all
6959 my @commitlist = $head ? parse_commits($head, 17) : ();
6960 if (@commitlist) {
6961 git_print_header_div('shortlog');
6962 git_shortlog_body(\@commitlist, 0, 15, $refs,
6963 $#commitlist <= 15 ? undef :
6964 $cgi->a({-href => href(action=>"shortlog")}, "..."));
6967 if (@taglist) {
6968 git_print_header_div('tags');
6969 git_tags_body(\@taglist, 0, 15,
6970 $#taglist <= 15 ? undef :
6971 $cgi->a({-href => href(action=>"tags")}, "..."));
6974 if (@headlist) {
6975 git_print_header_div('heads');
6976 git_heads_body(\@headlist, $head, 0, 15,
6977 $#headlist <= 15 ? undef :
6978 $cgi->a({-href => href(action=>"heads")}, "..."));
6981 if (%remotedata) {
6982 git_print_header_div('remotes');
6983 git_remotes_body(\%remotedata, 15, $head);
6986 if (@forklist) {
6987 git_print_header_div('forks');
6988 git_project_list_body(\@forklist, 'age', 0, 15,
6989 $#forklist <= 15 ? undef :
6990 $cgi->a({-href => href(action=>"forks")}, "..."),
6991 'no_header');
6994 git_footer_html();
6997 sub git_tag {
6998 my %tag = parse_tag($hash);
7000 if (! %tag) {
7001 die_error(404, "Unknown tag object");
7004 my $head = git_get_head_hash($project);
7005 git_header_html();
7006 git_print_page_nav('','', $head,undef,$head);
7007 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
7008 print "<div class=\"title_text\">\n" .
7009 "<table class=\"object_header\">\n" .
7010 "<tr>\n" .
7011 "<td>object</td>\n" .
7012 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
7013 $tag{'object'}) . "</td>\n" .
7014 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
7015 $tag{'type'}) . "</td>\n" .
7016 "</tr>\n";
7017 if (defined($tag{'author'})) {
7018 git_print_authorship_rows(\%tag, 'author');
7020 print "</table>\n\n" .
7021 "</div>\n";
7022 print "<div class=\"page_body\">";
7023 my $comment = $tag{'comment'};
7024 foreach my $line (@$comment) {
7025 chomp $line;
7026 print esc_html($line, -nbsp=>1) . "<br/>\n";
7028 print "</div>\n";
7029 git_footer_html();
7032 sub git_blame_common {
7033 my $format = shift || 'porcelain';
7034 if ($format eq 'porcelain' && $input_params{'javascript'}) {
7035 $format = 'incremental';
7036 $action = 'blame_incremental'; # for page title etc
7039 # permissions
7040 gitweb_check_feature('blame')
7041 or die_error(403, "Blame view not allowed");
7043 # error checking
7044 die_error(400, "No file name given") unless $file_name;
7045 $hash_base ||= git_get_head_hash($project);
7046 die_error(404, "Couldn't find base commit") unless $hash_base;
7047 my %co = parse_commit($hash_base)
7048 or die_error(404, "Commit not found");
7049 my $ftype = "blob";
7050 if (!defined $hash) {
7051 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
7052 or die_error(404, "Error looking up file");
7053 } else {
7054 $ftype = git_get_type($hash);
7055 if ($ftype !~ "blob") {
7056 die_error(400, "Object is not a blob");
7060 my $fd;
7061 if ($format eq 'incremental') {
7062 # get file contents (as base)
7063 defined($fd = git_cmd_pipe 'cat-file', 'blob', $hash)
7064 or die_error(500, "Open git-cat-file failed");
7065 } elsif ($format eq 'data') {
7066 # run git-blame --incremental
7067 defined($fd = git_cmd_pipe "blame", "--incremental",
7068 $hash_base, "--", $file_name)
7069 or die_error(500, "Open git-blame --incremental failed");
7070 } else {
7071 # run git-blame --porcelain
7072 defined($fd = git_cmd_pipe "blame", '-p',
7073 $hash_base, '--', $file_name)
7074 or die_error(500, "Open git-blame --porcelain failed");
7077 # incremental blame data returns early
7078 if ($format eq 'data') {
7079 print $cgi->header(
7080 -type=>"text/plain", -charset => "utf-8",
7081 -status=> "200 OK");
7082 local $| = 1; # output autoflush
7083 while (<$fd>) {
7084 print to_utf8($_);
7086 close $fd
7087 or print "ERROR $!\n";
7089 print 'END';
7090 if (defined $t0 && gitweb_check_feature('timed')) {
7091 print ' '.
7092 tv_interval($t0, [ gettimeofday() ]).
7093 ' '.$number_of_git_cmds;
7095 print "\n";
7097 return;
7100 # page header
7101 git_header_html();
7102 my $formats_nav =
7103 $cgi->a({-href => href(action=>"blob", -replay=>1)},
7104 "blob") .
7105 " | ";
7106 if ($format eq 'incremental') {
7107 $formats_nav .=
7108 $cgi->a({-href => href(action=>"blame", javascript=>0, -replay=>1)},
7109 "blame") . " (non-incremental)";
7110 } else {
7111 $formats_nav .=
7112 $cgi->a({-href => href(action=>"blame_incremental", -replay=>1)},
7113 "blame") . " (incremental)";
7115 $formats_nav .=
7116 " | " .
7117 $cgi->a({-href => href(action=>"history", -replay=>1)},
7118 "history") .
7119 " | " .
7120 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
7121 "HEAD");
7122 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7123 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7124 git_print_page_path($file_name, $ftype, $hash_base);
7126 # page body
7127 if ($format eq 'incremental') {
7128 print "<noscript>\n<div class=\"error\"><center><b>\n".
7129 "This page requires JavaScript to run.\n Use ".
7130 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
7131 'this page').
7132 " instead.\n".
7133 "</b></center></div>\n</noscript>\n";
7135 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
7138 print qq!<div class="page_body">\n!;
7139 print qq!<div id="progress_info">... / ...</div>\n!
7140 if ($format eq 'incremental');
7141 print qq!<table id="blame_table" class="blame" width="100%">\n!.
7142 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
7143 qq!<thead>\n!.
7144 qq!<tr><th>Commit</th><th>Line</th><th>Data</th></tr>\n!.
7145 qq!</thead>\n!.
7146 qq!<tbody>\n!;
7148 my @rev_color = qw(light dark);
7149 my $num_colors = scalar(@rev_color);
7150 my $current_color = 0;
7152 if ($format eq 'incremental') {
7153 my $color_class = $rev_color[$current_color];
7155 #contents of a file
7156 my $linenr = 0;
7157 LINE:
7158 while (my $line = to_utf8(scalar <$fd>)) {
7159 chomp $line;
7160 $linenr++;
7162 print qq!<tr id="l$linenr" class="$color_class">!.
7163 qq!<td class="sha1"><a href=""> </a></td>!.
7164 qq!<td class="linenr">!.
7165 qq!<a class="linenr" href="">$linenr</a></td>!;
7166 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
7167 print qq!</tr>\n!;
7170 } else { # porcelain, i.e. ordinary blame
7171 my %metainfo = (); # saves information about commits
7173 # blame data
7174 LINE:
7175 while (my $line = to_utf8(scalar <$fd>)) {
7176 chomp $line;
7177 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
7178 # no <lines in group> for subsequent lines in group of lines
7179 my ($full_rev, $orig_lineno, $lineno, $group_size) =
7180 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
7181 if (!exists $metainfo{$full_rev}) {
7182 $metainfo{$full_rev} = { 'nprevious' => 0 };
7184 my $meta = $metainfo{$full_rev};
7185 my $data;
7186 while ($data = to_utf8(scalar <$fd>)) {
7187 chomp $data;
7188 last if ($data =~ s/^\t//); # contents of line
7189 if ($data =~ /^(\S+)(?: (.*))?$/) {
7190 $meta->{$1} = $2 unless exists $meta->{$1};
7192 if ($data =~ /^previous /) {
7193 $meta->{'nprevious'}++;
7196 my $short_rev = substr($full_rev, 0, 8);
7197 my $author = $meta->{'author'};
7198 my %date =
7199 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
7200 my $date = $date{'iso-tz'};
7201 if ($group_size) {
7202 $current_color = ($current_color + 1) % $num_colors;
7204 my $tr_class = $rev_color[$current_color];
7205 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
7206 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
7207 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
7208 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
7209 if ($group_size) {
7210 print "<td class=\"sha1\"";
7211 print " title=\"". esc_html($author) . ", $date\"";
7212 print " rowspan=\"$group_size\"" if ($group_size > 1);
7213 print ">";
7214 print $cgi->a({-href => href(action=>"commit",
7215 hash=>$full_rev,
7216 file_name=>$file_name)},
7217 esc_html($short_rev));
7218 if ($group_size >= 2) {
7219 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
7220 if (@author_initials) {
7221 print "<br />" .
7222 esc_html(join('', @author_initials));
7223 # or join('.', ...)
7226 print "</td>\n";
7228 # 'previous' <sha1 of parent commit> <filename at commit>
7229 if (exists $meta->{'previous'} &&
7230 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
7231 $meta->{'parent'} = $1;
7232 $meta->{'file_parent'} = unquote($2);
7234 my $linenr_commit =
7235 exists($meta->{'parent'}) ?
7236 $meta->{'parent'} : $full_rev;
7237 my $linenr_filename =
7238 exists($meta->{'file_parent'}) ?
7239 $meta->{'file_parent'} : unquote($meta->{'filename'});
7240 my $blamed = href(action => 'blame',
7241 file_name => $linenr_filename,
7242 hash_base => $linenr_commit);
7243 print "<td class=\"linenr\">";
7244 print $cgi->a({ -href => "$blamed#l$orig_lineno",
7245 -class => "linenr" },
7246 esc_html($lineno));
7247 print "</td>";
7248 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
7249 print "</tr>\n";
7250 } # end while
7254 # footer
7255 print "</tbody>\n".
7256 "</table>\n"; # class="blame"
7257 print "</div>\n"; # class="blame_body"
7258 close $fd
7259 or print "Reading blob failed\n";
7261 git_footer_html();
7264 sub git_blame {
7265 git_blame_common();
7268 sub git_blame_incremental {
7269 git_blame_common('incremental');
7272 sub git_blame_data {
7273 git_blame_common('data');
7276 sub git_tags {
7277 my $head = git_get_head_hash($project);
7278 git_header_html();
7279 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
7280 git_print_header_div('summary', $project);
7282 my @tagslist = git_get_tags_list();
7283 if (@tagslist) {
7284 git_tags_body(\@tagslist);
7286 git_footer_html();
7289 sub git_heads {
7290 my $head = git_get_head_hash($project);
7291 git_header_html();
7292 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
7293 git_print_header_div('summary', $project);
7295 my @headslist = git_get_heads_list();
7296 if (@headslist) {
7297 git_heads_body(\@headslist, $head);
7299 git_footer_html();
7302 # used both for single remote view and for list of all the remotes
7303 sub git_remotes {
7304 gitweb_check_feature('remote_heads')
7305 or die_error(403, "Remote heads view is disabled");
7307 my $head = git_get_head_hash($project);
7308 my $remote = $input_params{'hash'};
7310 my $remotedata = git_get_remotes_list($remote);
7311 die_error(500, "Unable to get remote information") unless defined $remotedata;
7313 unless (%$remotedata) {
7314 die_error(404, defined $remote ?
7315 "Remote $remote not found" :
7316 "No remotes found");
7319 git_header_html(undef, undef, -action_extra => $remote);
7320 git_print_page_nav('', '', $head, undef, $head,
7321 format_ref_views($remote ? '' : 'remotes'));
7323 fill_remote_heads($remotedata);
7324 if (defined $remote) {
7325 git_print_header_div('remotes', "$remote remote for $project");
7326 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
7327 } else {
7328 git_print_header_div('summary', "$project remotes");
7329 git_remotes_body($remotedata, undef, $head);
7332 git_footer_html();
7335 sub git_blob_plain {
7336 my $type = shift;
7337 my $expires;
7339 if (!defined $hash) {
7340 if (defined $file_name) {
7341 my $base = $hash_base || git_get_head_hash($project);
7342 $hash = git_get_hash_by_path($base, $file_name, "blob")
7343 or die_error(404, "Cannot find file");
7344 } else {
7345 die_error(400, "No file name defined");
7347 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7348 # blobs defined by non-textual hash id's can be cached
7349 $expires = "+1d";
7352 defined(my $fd = git_cmd_pipe "cat-file", "blob", $hash)
7353 or die_error(500, "Open git-cat-file blob '$hash' failed");
7354 binmode($fd);
7356 # content-type (can include charset)
7357 my $leader;
7358 ($type, $leader) = blob_contenttype($fd, $file_name, $type);
7360 # "save as" filename, even when no $file_name is given
7361 my $save_as = "$hash";
7362 if (defined $file_name) {
7363 $save_as = $file_name;
7364 } elsif ($type =~ m/^text\//) {
7365 $save_as .= '.txt';
7368 # With XSS prevention on, blobs of all types except a few known safe
7369 # ones are served with "Content-Disposition: attachment" to make sure
7370 # they don't run in our security domain. For certain image types,
7371 # blob view writes an <img> tag referring to blob_plain view, and we
7372 # want to be sure not to break that by serving the image as an
7373 # attachment (though Firefox 3 doesn't seem to care).
7374 my $sandbox = $prevent_xss &&
7375 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
7377 # serve text/* as text/plain
7378 if ($prevent_xss &&
7379 ($type =~ m!^text/[a-z]+\b(.*)$! ||
7380 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
7381 my $rest = $1;
7382 $rest = defined $rest ? $rest : '';
7383 $type = "text/plain$rest";
7386 print $cgi->header(
7387 -type => $type,
7388 -expires => $expires,
7389 -content_disposition =>
7390 ($sandbox ? 'attachment' : 'inline')
7391 . '; filename="' . $save_as . '"');
7392 binmode STDOUT, ':raw';
7393 $fcgi_raw_mode = 1;
7394 print $leader if defined $leader;
7395 my $buf;
7396 while (read($fd, $buf, 32768)) {
7397 print $buf;
7399 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7400 $fcgi_raw_mode = 0;
7401 close $fd;
7404 sub git_blob {
7405 my $expires;
7407 if (!defined $hash) {
7408 if (defined $file_name) {
7409 my $base = $hash_base || git_get_head_hash($project);
7410 $hash = git_get_hash_by_path($base, $file_name, "blob")
7411 or die_error(404, "Cannot find file");
7412 } else {
7413 die_error(400, "No file name defined");
7415 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7416 # blobs defined by non-textual hash id's can be cached
7417 $expires = "+1d";
7420 my $have_blame = gitweb_check_feature('blame');
7421 defined(my $fd = git_cmd_pipe "cat-file", "blob", $hash)
7422 or die_error(500, "Couldn't cat $file_name, $hash");
7423 binmode($fd);
7424 my $mimetype = blob_mimetype($fd, $file_name);
7425 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
7426 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
7427 close $fd;
7428 return git_blob_plain($mimetype);
7430 # we can have blame only for text/* mimetype
7431 $have_blame &&= ($mimetype =~ m!^text/!);
7433 my $highlight = gitweb_check_feature('highlight') && defined $highlight_bin;
7434 my $syntax = guess_file_syntax($fd, $mimetype, $file_name) if $highlight;
7435 my $highlight_mode_active;
7436 ($fd, $highlight_mode_active) = run_highlighter($fd, $syntax) if $syntax;
7438 git_header_html(undef, $expires);
7439 my $formats_nav = '';
7440 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7441 if (defined $file_name) {
7442 if ($have_blame) {
7443 $formats_nav .=
7444 $cgi->a({-href => href(action=>"blame", -replay=>1)},
7445 "blame") .
7446 " | ";
7448 $formats_nav .=
7449 $cgi->a({-href => href(action=>"history", -replay=>1)},
7450 "history") .
7451 " | " .
7452 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7453 "raw") .
7454 " | " .
7455 $cgi->a({-href => href(action=>"blob",
7456 hash_base=>"HEAD", file_name=>$file_name)},
7457 "HEAD");
7458 } else {
7459 $formats_nav .=
7460 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
7461 "raw");
7463 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7464 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7465 } else {
7466 print "<div class=\"page_nav\">\n" .
7467 "<br/><br/></div>\n" .
7468 "<div class=\"title\">".esc_html($hash)."</div>\n";
7470 git_print_page_path($file_name, "blob", $hash_base);
7471 print "<div class=\"page_body\">\n";
7472 if ($mimetype =~ m!^image/!) {
7473 print qq!<img class="blob" type="!.esc_attr($mimetype).qq!"!;
7474 if ($file_name) {
7475 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
7477 print qq! src="! .
7478 href(action=>"blob_plain", hash=>$hash,
7479 hash_base=>$hash_base, file_name=>$file_name) .
7480 qq!" />\n!;
7481 } else {
7482 my $nr;
7483 while (my $line = to_utf8(scalar <$fd>)) {
7484 chomp $line;
7485 $nr++;
7486 $line = untabify($line);
7487 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
7488 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
7489 $highlight_mode_active ? sanitize($line) : esc_html($line, -nbsp=>1);
7492 close $fd
7493 or print "Reading blob failed.\n";
7494 print "</div>";
7495 git_footer_html();
7498 sub git_tree {
7499 if (!defined $hash_base) {
7500 $hash_base = "HEAD";
7502 if (!defined $hash) {
7503 if (defined $file_name) {
7504 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
7505 } else {
7506 $hash = $hash_base;
7509 die_error(404, "No such tree") unless defined($hash);
7511 my $show_sizes = gitweb_check_feature('show-sizes');
7512 my $have_blame = gitweb_check_feature('blame');
7514 my @entries = ();
7516 local $/ = "\0";
7517 defined(my $fd = git_cmd_pipe "ls-tree", '-z',
7518 ($show_sizes ? '-l' : ()), @extra_options, $hash)
7519 or die_error(500, "Open git-ls-tree failed");
7520 @entries = map { chomp; to_utf8($_) } <$fd>;
7521 close $fd
7522 or die_error(404, "Reading tree failed");
7525 my $refs = git_get_references();
7526 my $ref = format_ref_marker($refs, $hash_base);
7527 git_header_html();
7528 my $basedir = '';
7529 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
7530 my @views_nav = ();
7531 if (defined $file_name) {
7532 push @views_nav,
7533 $cgi->a({-href => href(action=>"history", -replay=>1)},
7534 "history"),
7535 $cgi->a({-href => href(action=>"tree",
7536 hash_base=>"HEAD", file_name=>$file_name)},
7537 "HEAD"),
7539 my $snapshot_links = format_snapshot_links($hash);
7540 if (defined $snapshot_links) {
7541 # FIXME: Should be available when we have no hash base as well.
7542 push @views_nav, $snapshot_links;
7544 git_print_page_nav('tree','', $hash_base, undef, undef,
7545 join(' | ', @views_nav));
7546 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash_base);
7547 } else {
7548 undef $hash_base;
7549 print "<div class=\"page_nav\">\n";
7550 print "<br/><br/></div>\n";
7551 print "<div class=\"title\">".esc_html($hash)."</div>\n";
7553 if (defined $file_name) {
7554 $basedir = $file_name;
7555 if ($basedir ne '' && substr($basedir, -1) ne '/') {
7556 $basedir .= '/';
7558 git_print_page_path($file_name, 'tree', $hash_base);
7560 print "<div class=\"page_body\">\n";
7561 print "<table class=\"tree\">\n";
7562 my $alternate = 1;
7563 # '..' (top directory) link if possible
7564 if (defined $hash_base &&
7565 defined $file_name && $file_name =~ m![^/]+$!) {
7566 if ($alternate) {
7567 print "<tr class=\"dark\">\n";
7568 } else {
7569 print "<tr class=\"light\">\n";
7571 $alternate ^= 1;
7573 my $up = $file_name;
7574 $up =~ s!/?[^/]+$!!;
7575 undef $up unless $up;
7576 # based on git_print_tree_entry
7577 print '<td class="mode">' . mode_str('040000') . "</td>\n";
7578 print '<td class="size">&nbsp;</td>'."\n" if $show_sizes;
7579 print '<td class="list">';
7580 print $cgi->a({-href => href(action=>"tree",
7581 hash_base=>$hash_base,
7582 file_name=>$up)},
7583 "..");
7584 print "</td>\n";
7585 print "<td class=\"link\"></td>\n";
7587 print "</tr>\n";
7589 foreach my $line (@entries) {
7590 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
7592 if ($alternate) {
7593 print "<tr class=\"dark\">\n";
7594 } else {
7595 print "<tr class=\"light\">\n";
7597 $alternate ^= 1;
7599 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
7601 print "</tr>\n";
7603 print "</table>\n" .
7604 "</div>";
7605 git_footer_html();
7608 sub sanitize_for_filename {
7609 my $name = shift;
7611 $name =~ s!/!-!g;
7612 $name =~ s/[^[:alnum:]_.-]//g;
7614 return $name;
7617 sub snapshot_name {
7618 my ($project, $hash) = @_;
7620 # path/to/project.git -> project
7621 # path/to/project/.git -> project
7622 my $name = to_utf8($project);
7623 $name =~ s,([^/])/*\.git$,$1,;
7624 $name = sanitize_for_filename(basename($name));
7626 my $ver = $hash;
7627 if ($hash =~ /^[0-9a-fA-F]+$/) {
7628 # shorten SHA-1 hash
7629 my $full_hash = git_get_full_hash($project, $hash);
7630 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
7631 $ver = git_get_short_hash($project, $hash);
7633 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
7634 # tags don't need shortened SHA-1 hash
7635 $ver = $1;
7636 } else {
7637 # branches and other need shortened SHA-1 hash
7638 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
7639 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
7640 my $ref_dir = (defined $1) ? $1 : '';
7641 $ver = $2;
7643 $ref_dir = sanitize_for_filename($ref_dir);
7644 # for refs neither in heads nor remotes we want to
7645 # add a ref dir to archive name
7646 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
7647 $ver = $ref_dir . '-' . $ver;
7650 $ver .= '-' . git_get_short_hash($project, $hash);
7652 # special case of sanitization for filename - we change
7653 # slashes to dots instead of dashes
7654 # in case of hierarchical branch names
7655 $ver =~ s!/!.!g;
7656 $ver =~ s/[^[:alnum:]_.-]//g;
7658 # name = project-version_string
7659 $name = "$name-$ver";
7661 return wantarray ? ($name, $name) : $name;
7664 sub exit_if_unmodified_since {
7665 my ($latest_epoch) = @_;
7666 our $cgi;
7668 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
7669 if (defined $if_modified) {
7670 my $since;
7671 if (eval { require HTTP::Date; 1; }) {
7672 $since = HTTP::Date::str2time($if_modified);
7673 } elsif (eval { require Time::ParseDate; 1; }) {
7674 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
7676 if (defined $since && $latest_epoch <= $since) {
7677 my %latest_date = parse_date($latest_epoch);
7678 print $cgi->header(
7679 -last_modified => $latest_date{'rfc2822'},
7680 -status => '304 Not Modified');
7681 goto DONE_GITWEB;
7686 sub git_snapshot {
7687 my $format = $input_params{'snapshot_format'};
7688 if (!@snapshot_fmts) {
7689 die_error(403, "Snapshots not allowed");
7691 # default to first supported snapshot format
7692 $format ||= $snapshot_fmts[0];
7693 if ($format !~ m/^[a-z0-9]+$/) {
7694 die_error(400, "Invalid snapshot format parameter");
7695 } elsif (!exists($known_snapshot_formats{$format})) {
7696 die_error(400, "Unknown snapshot format");
7697 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
7698 die_error(403, "Snapshot format not allowed");
7699 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
7700 die_error(403, "Unsupported snapshot format");
7703 my $type = git_get_type("$hash^{}");
7704 if (!$type) {
7705 die_error(404, 'Object does not exist');
7706 } elsif ($type eq 'blob') {
7707 die_error(400, 'Object is not a tree-ish');
7710 my ($name, $prefix) = snapshot_name($project, $hash);
7711 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
7713 my %co = parse_commit($hash);
7714 exit_if_unmodified_since($co{'committer_epoch'}) if %co;
7716 my @cmd = (
7717 git_cmd(), 'archive',
7718 "--format=$known_snapshot_formats{$format}{'format'}",
7719 "--prefix=$prefix/", $hash);
7720 if (exists $known_snapshot_formats{$format}{'compressor'}) {
7721 @cmd = ($posix_shell_bin, '-c', quote_command(@cmd) .
7722 ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}}));
7725 $filename =~ s/(["\\])/\\$1/g;
7726 my %latest_date;
7727 if (%co) {
7728 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
7731 print $cgi->header(
7732 -type => $known_snapshot_formats{$format}{'type'},
7733 -content_disposition => 'inline; filename="' . $filename . '"',
7734 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
7735 -status => '200 OK');
7737 defined(my $fd = cmd_pipe @cmd)
7738 or die_error(500, "Execute git-archive failed");
7739 binmode($fd);
7740 binmode STDOUT, ':raw';
7741 $fcgi_raw_mode = 1;
7742 my $buf;
7743 while (read($fd, $buf, 32768)) {
7744 print $buf;
7746 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
7747 $fcgi_raw_mode = 0;
7748 close $fd;
7751 sub git_log_generic {
7752 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
7754 my $head = git_get_head_hash($project);
7755 if (!defined $base) {
7756 $base = $head;
7758 if (!defined $page) {
7759 $page = 0;
7761 my $refs = git_get_references();
7763 my $commit_hash = $base;
7764 if (defined $parent) {
7765 $commit_hash = "$parent..$base";
7767 my @commitlist =
7768 parse_commits($commit_hash, 101, (100 * $page),
7769 defined $file_name ? ($file_name, "--full-history") : ());
7771 my $ftype;
7772 if (!defined $file_hash && defined $file_name) {
7773 # some commits could have deleted file in question,
7774 # and not have it in tree, but one of them has to have it
7775 for (my $i = 0; $i < @commitlist; $i++) {
7776 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
7777 last if defined $file_hash;
7780 if (defined $file_hash) {
7781 $ftype = git_get_type($file_hash);
7783 if (defined $file_name && !defined $ftype) {
7784 die_error(500, "Unknown type of object");
7786 my %co;
7787 if (defined $file_name) {
7788 %co = parse_commit($base)
7789 or die_error(404, "Unknown commit object");
7793 my $paging_nav = format_paging_nav($fmt_name, $page, $#commitlist >= 100);
7794 my $next_link = '';
7795 if ($#commitlist >= 100) {
7796 $next_link =
7797 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7798 -accesskey => "n", -title => "Alt-n"}, "next");
7800 my $patch_max = gitweb_get_feature('patches');
7801 if ($patch_max && !defined $file_name) {
7802 if ($patch_max < 0 || @commitlist <= $patch_max) {
7803 $paging_nav .= " &sdot; " .
7804 $cgi->a({-href => href(action=>"patches", -replay=>1)},
7805 "patches");
7809 git_header_html();
7810 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
7811 if (defined $file_name) {
7812 git_print_header_div('commit', esc_html($co{'title'}), $base);
7813 } else {
7814 git_print_header_div('summary', $project)
7816 git_print_page_path($file_name, $ftype, $hash_base)
7817 if (defined $file_name);
7819 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
7820 $file_name, $file_hash, $ftype);
7822 git_footer_html();
7825 sub git_log {
7826 git_log_generic('log', \&git_log_body,
7827 $hash, $hash_parent);
7830 sub git_commit {
7831 $hash ||= $hash_base || "HEAD";
7832 my %co = parse_commit($hash)
7833 or die_error(404, "Unknown commit object");
7835 my $parent = $co{'parent'};
7836 my $parents = $co{'parents'}; # listref
7838 # we need to prepare $formats_nav before any parameter munging
7839 my $formats_nav;
7840 if (!defined $parent) {
7841 # --root commitdiff
7842 $formats_nav .= '(initial)';
7843 } elsif (@$parents == 1) {
7844 # single parent commit
7845 $formats_nav .=
7846 '(parent: ' .
7847 $cgi->a({-href => href(action=>"commit",
7848 hash=>$parent)},
7849 esc_html(substr($parent, 0, 7))) .
7850 ')';
7851 } else {
7852 # merge commit
7853 $formats_nav .=
7854 '(merge: ' .
7855 join(' ', map {
7856 $cgi->a({-href => href(action=>"commit",
7857 hash=>$_)},
7858 esc_html(substr($_, 0, 7)));
7859 } @$parents ) .
7860 ')';
7862 if (gitweb_check_feature('patches') && @$parents <= 1) {
7863 $formats_nav .= " | " .
7864 $cgi->a({-href => href(action=>"patch", -replay=>1)},
7865 "patch");
7868 if (!defined $parent) {
7869 $parent = "--root";
7871 my @difftree;
7872 defined(my $fd = git_cmd_pipe "diff-tree", '-r', "--no-commit-id",
7873 @diff_opts,
7874 (@$parents <= 1 ? $parent : '-c'),
7875 $hash, "--")
7876 or die_error(500, "Open git-diff-tree failed");
7877 @difftree = map { chomp; to_utf8($_) } <$fd>;
7878 close $fd or die_error(404, "Reading git-diff-tree failed");
7880 # non-textual hash id's can be cached
7881 my $expires;
7882 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
7883 $expires = "+1d";
7885 my $refs = git_get_references();
7886 my $ref = format_ref_marker($refs, $co{'id'});
7888 git_header_html(undef, $expires);
7889 git_print_page_nav('commit', '',
7890 $hash, $co{'tree'}, $hash,
7891 $formats_nav);
7893 if (defined $co{'parent'}) {
7894 git_print_header_div('commitdiff', esc_html($co{'title'}) . $ref, $hash);
7895 } else {
7896 git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
7898 print "<div class=\"title_text\">\n" .
7899 "<table class=\"object_header\">\n";
7900 git_print_authorship_rows(\%co);
7901 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
7902 print "<tr>" .
7903 "<td>tree</td>" .
7904 "<td class=\"sha1\">" .
7905 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
7906 class => "list"}, $co{'tree'}) .
7907 "</td>" .
7908 "<td class=\"link\">" .
7909 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
7910 "tree");
7911 my $snapshot_links = format_snapshot_links($hash);
7912 if (defined $snapshot_links) {
7913 print " | " . $snapshot_links;
7915 print "</td>" .
7916 "</tr>\n";
7918 foreach my $par (@$parents) {
7919 print "<tr>" .
7920 "<td>parent</td>" .
7921 "<td class=\"sha1\">" .
7922 $cgi->a({-href => href(action=>"commit", hash=>$par),
7923 class => "list"}, $par) .
7924 "</td>" .
7925 "<td class=\"link\">" .
7926 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
7927 " | " .
7928 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
7929 "</td>" .
7930 "</tr>\n";
7932 print "</table>".
7933 "</div>\n";
7935 print "<div class=\"page_body\">\n";
7936 git_print_log($co{'comment'});
7937 print "</div>\n";
7939 git_difftree_body(\@difftree, $hash, @$parents);
7941 git_footer_html();
7944 sub git_object {
7945 # object is defined by:
7946 # - hash or hash_base alone
7947 # - hash_base and file_name
7948 my $type;
7950 # - hash or hash_base alone
7951 if ($hash || ($hash_base && !defined $file_name)) {
7952 my $object_id = $hash || $hash_base;
7954 defined(my $fd = git_cmd_pipe 'cat-file', '-t', $object_id)
7955 or die_error(404, "Object does not exist");
7956 $type = <$fd>;
7957 chomp $type;
7958 close $fd
7959 or die_error(404, "Object does not exist");
7961 # - hash_base and file_name
7962 } elsif ($hash_base && defined $file_name) {
7963 $file_name =~ s,/+$,,;
7965 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
7966 or die_error(404, "Base object does not exist");
7968 # here errors should not happen
7969 defined(my $fd = git_cmd_pipe "ls-tree", $hash_base, "--", $file_name)
7970 or die_error(500, "Open git-ls-tree failed");
7971 my $line = to_utf8(scalar <$fd>);
7972 close $fd;
7974 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
7975 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
7976 die_error(404, "File or directory for given base does not exist");
7978 $type = $2;
7979 $hash = $3;
7980 } else {
7981 die_error(400, "Not enough information to find object");
7984 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
7985 hash=>$hash, hash_base=>$hash_base,
7986 file_name=>$file_name),
7987 -status => '302 Found');
7990 sub git_blobdiff {
7991 my $format = shift || 'html';
7992 my $diff_style = $input_params{'diff_style'} || 'inline';
7994 my $fd;
7995 my @difftree;
7996 my %diffinfo;
7997 my $expires;
7999 # preparing $fd and %diffinfo for git_patchset_body
8000 # new style URI
8001 if (defined $hash_base && defined $hash_parent_base) {
8002 if (defined $file_name) {
8003 # read raw output
8004 defined($fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
8005 $hash_parent_base, $hash_base,
8006 "--", (defined $file_parent ? $file_parent : ()), $file_name)
8007 or die_error(500, "Open git-diff-tree failed");
8008 @difftree = map { chomp; to_utf8($_) } <$fd>;
8009 close $fd
8010 or die_error(404, "Reading git-diff-tree failed");
8011 @difftree
8012 or die_error(404, "Blob diff not found");
8014 } elsif (defined $hash &&
8015 $hash =~ /[0-9a-fA-F]{40}/) {
8016 # try to find filename from $hash
8018 # read filtered raw output
8019 defined($fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
8020 $hash_parent_base, $hash_base, "--")
8021 or die_error(500, "Open git-diff-tree failed");
8022 @difftree =
8023 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
8024 # $hash == to_id
8025 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
8026 map { chomp; to_utf8($_) } <$fd>;
8027 close $fd
8028 or die_error(404, "Reading git-diff-tree failed");
8029 @difftree
8030 or die_error(404, "Blob diff not found");
8032 } else {
8033 die_error(400, "Missing one of the blob diff parameters");
8036 if (@difftree > 1) {
8037 die_error(400, "Ambiguous blob diff specification");
8040 %diffinfo = parse_difftree_raw_line($difftree[0]);
8041 $file_parent ||= $diffinfo{'from_file'} || $file_name;
8042 $file_name ||= $diffinfo{'to_file'};
8044 $hash_parent ||= $diffinfo{'from_id'};
8045 $hash ||= $diffinfo{'to_id'};
8047 # non-textual hash id's can be cached
8048 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
8049 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
8050 $expires = '+1d';
8053 # open patch output
8054 defined($fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
8055 '-p', ($format eq 'html' ? "--full-index" : ()),
8056 $hash_parent_base, $hash_base,
8057 "--", (defined $file_parent ? $file_parent : ()), $file_name)
8058 or die_error(500, "Open git-diff-tree failed");
8061 # old/legacy style URI -- not generated anymore since 1.4.3.
8062 if (!%diffinfo) {
8063 die_error('404 Not Found', "Missing one of the blob diff parameters")
8066 # header
8067 if ($format eq 'html') {
8068 my $formats_nav =
8069 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
8070 "raw");
8071 $formats_nav .= diff_style_nav($diff_style);
8072 git_header_html(undef, $expires);
8073 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
8074 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
8075 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
8076 } else {
8077 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
8078 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
8080 if (defined $file_name) {
8081 git_print_page_path($file_name, "blob", $hash_base);
8082 } else {
8083 print "<div class=\"page_path\"></div>\n";
8086 } elsif ($format eq 'plain') {
8087 print $cgi->header(
8088 -type => 'text/plain',
8089 -charset => 'utf-8',
8090 -expires => $expires,
8091 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
8093 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
8095 } else {
8096 die_error(400, "Unknown blobdiff format");
8099 # patch
8100 if ($format eq 'html') {
8101 print "<div class=\"page_body\">\n";
8103 git_patchset_body($fd, $diff_style,
8104 [ \%diffinfo ], $hash_base, $hash_parent_base);
8105 close $fd;
8107 print "</div>\n"; # class="page_body"
8108 git_footer_html();
8110 } else {
8111 while (my $line = to_utf8(scalar <$fd>)) {
8112 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
8113 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
8115 print $line;
8117 last if $line =~ m!^\+\+\+!;
8119 while (<$fd>) {
8120 print to_utf8($_);
8122 close $fd;
8126 sub git_blobdiff_plain {
8127 git_blobdiff('plain');
8130 # assumes that it is added as later part of already existing navigation,
8131 # so it returns "| foo | bar" rather than just "foo | bar"
8132 sub diff_style_nav {
8133 my ($diff_style, $is_combined) = @_;
8134 $diff_style ||= 'inline';
8136 return "" if ($is_combined);
8138 my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
8139 my %styles = @styles;
8140 @styles =
8141 @styles[ map { $_ * 2 } 0..$#styles/2 ];
8143 return join '',
8144 map { " | ".$_ }
8145 map {
8146 $_ eq $diff_style ? $styles{$_} :
8147 $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
8148 } @styles;
8151 sub git_commitdiff {
8152 my %params = @_;
8153 my $format = $params{-format} || 'html';
8154 my $diff_style = $input_params{'diff_style'} || 'inline';
8156 my ($patch_max) = gitweb_get_feature('patches');
8157 if ($format eq 'patch') {
8158 die_error(403, "Patch view not allowed") unless $patch_max;
8161 $hash ||= $hash_base || "HEAD";
8162 my %co = parse_commit($hash)
8163 or die_error(404, "Unknown commit object");
8165 # choose format for commitdiff for merge
8166 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
8167 $hash_parent = '--cc';
8169 # we need to prepare $formats_nav before almost any parameter munging
8170 my $formats_nav;
8171 if ($format eq 'html') {
8172 $formats_nav =
8173 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
8174 "raw");
8175 if ($patch_max && @{$co{'parents'}} <= 1) {
8176 $formats_nav .= " | " .
8177 $cgi->a({-href => href(action=>"patch", -replay=>1)},
8178 "patch");
8180 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
8182 if (defined $hash_parent &&
8183 $hash_parent ne '-c' && $hash_parent ne '--cc') {
8184 # commitdiff with two commits given
8185 my $hash_parent_short = $hash_parent;
8186 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
8187 $hash_parent_short = substr($hash_parent, 0, 7);
8189 $formats_nav .=
8190 ' (from';
8191 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
8192 if ($co{'parents'}[$i] eq $hash_parent) {
8193 $formats_nav .= ' parent ' . ($i+1);
8194 last;
8197 $formats_nav .= ': ' .
8198 $cgi->a({-href => href(-replay=>1,
8199 hash=>$hash_parent, hash_base=>undef)},
8200 esc_html($hash_parent_short)) .
8201 ')';
8202 } elsif (!$co{'parent'}) {
8203 # --root commitdiff
8204 $formats_nav .= ' (initial)';
8205 } elsif (scalar @{$co{'parents'}} == 1) {
8206 # single parent commit
8207 $formats_nav .=
8208 ' (parent: ' .
8209 $cgi->a({-href => href(-replay=>1,
8210 hash=>$co{'parent'}, hash_base=>undef)},
8211 esc_html(substr($co{'parent'}, 0, 7))) .
8212 ')';
8213 } else {
8214 # merge commit
8215 if ($hash_parent eq '--cc') {
8216 $formats_nav .= ' | ' .
8217 $cgi->a({-href => href(-replay=>1,
8218 hash=>$hash, hash_parent=>'-c')},
8219 'combined');
8220 } else { # $hash_parent eq '-c'
8221 $formats_nav .= ' | ' .
8222 $cgi->a({-href => href(-replay=>1,
8223 hash=>$hash, hash_parent=>'--cc')},
8224 'compact');
8226 $formats_nav .=
8227 ' (merge: ' .
8228 join(' ', map {
8229 $cgi->a({-href => href(-replay=>1,
8230 hash=>$_, hash_base=>undef)},
8231 esc_html(substr($_, 0, 7)));
8232 } @{$co{'parents'}} ) .
8233 ')';
8237 my $hash_parent_param = $hash_parent;
8238 if (!defined $hash_parent_param) {
8239 # --cc for multiple parents, --root for parentless
8240 $hash_parent_param =
8241 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
8244 # read commitdiff
8245 my $fd;
8246 my @difftree;
8247 if ($format eq 'html') {
8248 defined($fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
8249 "--no-commit-id", "--patch-with-raw", "--full-index",
8250 $hash_parent_param, $hash, "--")
8251 or die_error(500, "Open git-diff-tree failed");
8253 while (my $line = to_utf8(scalar <$fd>)) {
8254 chomp $line;
8255 # empty line ends raw part of diff-tree output
8256 last unless $line;
8257 push @difftree, scalar parse_difftree_raw_line($line);
8260 } elsif ($format eq 'plain') {
8261 defined($fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
8262 '-p', $hash_parent_param, $hash, "--")
8263 or die_error(500, "Open git-diff-tree failed");
8264 } elsif ($format eq 'patch') {
8265 # For commit ranges, we limit the output to the number of
8266 # patches specified in the 'patches' feature.
8267 # For single commits, we limit the output to a single patch,
8268 # diverging from the git-format-patch default.
8269 my @commit_spec = ();
8270 if ($hash_parent) {
8271 if ($patch_max > 0) {
8272 push @commit_spec, "-$patch_max";
8274 push @commit_spec, '-n', "$hash_parent..$hash";
8275 } else {
8276 if ($params{-single}) {
8277 push @commit_spec, '-1';
8278 } else {
8279 if ($patch_max > 0) {
8280 push @commit_spec, "-$patch_max";
8282 push @commit_spec, "-n";
8284 push @commit_spec, '--root', $hash;
8286 defined($fd = git_cmd_pipe "format-patch", @diff_opts,
8287 '--encoding=utf8', '--stdout', @commit_spec)
8288 or die_error(500, "Open git-format-patch failed");
8289 } else {
8290 die_error(400, "Unknown commitdiff format");
8293 # non-textual hash id's can be cached
8294 my $expires;
8295 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
8296 $expires = "+1d";
8299 # write commit message
8300 if ($format eq 'html') {
8301 my $refs = git_get_references();
8302 my $ref = format_ref_marker($refs, $co{'id'});
8304 git_header_html(undef, $expires);
8305 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
8306 git_print_header_div('commit', esc_html($co{'title'}) . $ref, $hash);
8307 print "<div class=\"title_text\">\n" .
8308 "<table class=\"object_header\">\n";
8309 git_print_authorship_rows(\%co);
8310 print "</table>".
8311 "</div>\n";
8312 print "<div class=\"page_body\">\n";
8313 if (@{$co{'comment'}} > 1) {
8314 print "<div class=\"log\">\n";
8315 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
8316 print "</div>\n"; # class="log"
8319 } elsif ($format eq 'plain') {
8320 my $refs = git_get_references("tags");
8321 my $tagname = git_get_rev_name_tags($hash);
8322 my $filename = basename($project) . "-$hash.patch";
8324 print $cgi->header(
8325 -type => 'text/plain',
8326 -charset => 'utf-8',
8327 -expires => $expires,
8328 -content_disposition => 'inline; filename="' . "$filename" . '"');
8329 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
8330 print "From: " . to_utf8($co{'author'}) . "\n";
8331 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
8332 print "Subject: " . to_utf8($co{'title'}) . "\n";
8334 print "X-Git-Tag: $tagname\n" if $tagname;
8335 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
8337 foreach my $line (@{$co{'comment'}}) {
8338 print to_utf8($line) . "\n";
8340 print "---\n\n";
8341 } elsif ($format eq 'patch') {
8342 my $filename = basename($project) . "-$hash.patch";
8344 print $cgi->header(
8345 -type => 'text/plain',
8346 -charset => 'utf-8',
8347 -expires => $expires,
8348 -content_disposition => 'inline; filename="' . "$filename" . '"');
8351 # write patch
8352 if ($format eq 'html') {
8353 my $use_parents = !defined $hash_parent ||
8354 $hash_parent eq '-c' || $hash_parent eq '--cc';
8355 git_difftree_body(\@difftree, $hash,
8356 $use_parents ? @{$co{'parents'}} : $hash_parent);
8357 print "<br/>\n";
8359 git_patchset_body($fd, $diff_style,
8360 \@difftree, $hash,
8361 $use_parents ? @{$co{'parents'}} : $hash_parent);
8362 close $fd;
8363 print "</div>\n"; # class="page_body"
8364 git_footer_html();
8366 } elsif ($format eq 'plain') {
8367 while (<$fd>) {
8368 print to_utf8($_);
8370 close $fd
8371 or print "Reading git-diff-tree failed\n";
8372 } elsif ($format eq 'patch') {
8373 while (<$fd>) {
8374 print to_utf8($_);
8376 close $fd
8377 or print "Reading git-format-patch failed\n";
8381 sub git_commitdiff_plain {
8382 git_commitdiff(-format => 'plain');
8385 # format-patch-style patches
8386 sub git_patch {
8387 git_commitdiff(-format => 'patch', -single => 1);
8390 sub git_patches {
8391 git_commitdiff(-format => 'patch');
8394 sub git_history {
8395 git_log_generic('history', \&git_history_body,
8396 $hash_base, $hash_parent_base,
8397 $file_name, $hash);
8400 sub git_search {
8401 $searchtype ||= 'commit';
8403 # check if appropriate features are enabled
8404 gitweb_check_feature('search')
8405 or die_error(403, "Search is disabled");
8406 if ($searchtype eq 'pickaxe') {
8407 # pickaxe may take all resources of your box and run for several minutes
8408 # with every query - so decide by yourself how public you make this feature
8409 gitweb_check_feature('pickaxe')
8410 or die_error(403, "Pickaxe search is disabled");
8412 if ($searchtype eq 'grep') {
8413 # grep search might be potentially CPU-intensive, too
8414 gitweb_check_feature('grep')
8415 or die_error(403, "Grep search is disabled");
8418 if (!defined $searchtext) {
8419 die_error(400, "Text field is empty");
8421 if (!defined $hash) {
8422 $hash = git_get_head_hash($project);
8424 my %co = parse_commit($hash);
8425 if (!%co) {
8426 die_error(404, "Unknown commit object");
8428 if (!defined $page) {
8429 $page = 0;
8432 if ($searchtype eq 'commit' ||
8433 $searchtype eq 'author' ||
8434 $searchtype eq 'committer') {
8435 git_search_message(%co);
8436 } elsif ($searchtype eq 'pickaxe') {
8437 git_search_changes(%co);
8438 } elsif ($searchtype eq 'grep') {
8439 git_search_files(%co);
8440 } else {
8441 die_error(400, "Unknown search type");
8445 sub git_search_help {
8446 git_header_html();
8447 git_print_page_nav('','', $hash,$hash,$hash);
8448 print <<EOT;
8449 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
8450 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
8451 the pattern entered is recognized as the POSIX extended
8452 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
8453 insensitive).</p>
8454 <dl>
8455 <dt><b>commit</b></dt>
8456 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
8458 my $have_grep = gitweb_check_feature('grep');
8459 if ($have_grep) {
8460 print <<EOT;
8461 <dt><b>grep</b></dt>
8462 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
8463 a different one) are searched for the given pattern. On large trees, this search can take
8464 a while and put some strain on the server, so please use it with some consideration. Note that
8465 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
8466 case-sensitive.</dd>
8469 print <<EOT;
8470 <dt><b>author</b></dt>
8471 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
8472 <dt><b>committer</b></dt>
8473 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
8475 my $have_pickaxe = gitweb_check_feature('pickaxe');
8476 if ($have_pickaxe) {
8477 print <<EOT;
8478 <dt><b>pickaxe</b></dt>
8479 <dd>All commits that caused the string to appear or disappear from any file (changes that
8480 added, removed or "modified" the string) will be listed. This search can take a while and
8481 takes a lot of strain on the server, so please use it wisely. Note that since you may be
8482 interested even in changes just changing the case as well, this search is case sensitive.</dd>
8485 print "</dl>\n";
8486 git_footer_html();
8489 sub git_shortlog {
8490 git_log_generic('shortlog', \&git_shortlog_body,
8491 $hash, $hash_parent);
8494 ## ......................................................................
8495 ## feeds (RSS, Atom; OPML)
8497 sub git_feed {
8498 my $format = shift || 'atom';
8499 my $have_blame = gitweb_check_feature('blame');
8501 # Atom: http://www.atomenabled.org/developers/syndication/
8502 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
8503 if ($format ne 'rss' && $format ne 'atom') {
8504 die_error(400, "Unknown web feed format");
8507 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
8508 my $head = $hash || 'HEAD';
8509 my @commitlist = parse_commits($head, 150, 0, $file_name);
8511 my %latest_commit;
8512 my %latest_date;
8513 my $content_type = "application/$format+xml";
8514 if (defined $cgi->http('HTTP_ACCEPT') &&
8515 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
8516 # browser (feed reader) prefers text/xml
8517 $content_type = 'text/xml';
8519 if (defined($commitlist[0])) {
8520 %latest_commit = %{$commitlist[0]};
8521 my $latest_epoch = $latest_commit{'committer_epoch'};
8522 exit_if_unmodified_since($latest_epoch);
8523 %latest_date = parse_date($latest_epoch, $latest_commit{'committer_tz'});
8525 print $cgi->header(
8526 -type => $content_type,
8527 -charset => 'utf-8',
8528 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
8529 -status => '200 OK');
8531 # Optimization: skip generating the body if client asks only
8532 # for Last-Modified date.
8533 return if ($cgi->request_method() eq 'HEAD');
8535 # header variables
8536 my $title = "$site_name - $project/$action";
8537 my $feed_type = 'log';
8538 if (defined $hash) {
8539 $title .= " - '$hash'";
8540 $feed_type = 'branch log';
8541 if (defined $file_name) {
8542 $title .= " :: $file_name";
8543 $feed_type = 'history';
8545 } elsif (defined $file_name) {
8546 $title .= " - $file_name";
8547 $feed_type = 'history';
8549 $title .= " $feed_type";
8550 $title = esc_html($title);
8551 my $descr = git_get_project_description($project);
8552 if (defined $descr) {
8553 $descr = esc_html($descr);
8554 } else {
8555 $descr = "$project " .
8556 ($format eq 'rss' ? 'RSS' : 'Atom') .
8557 " feed";
8559 my $owner = git_get_project_owner($project);
8560 $owner = esc_html($owner);
8562 #header
8563 my $alt_url;
8564 if (defined $file_name) {
8565 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
8566 } elsif (defined $hash) {
8567 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
8568 } else {
8569 $alt_url = href(-full=>1, action=>"summary");
8571 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
8572 if ($format eq 'rss') {
8573 print <<XML;
8574 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
8575 <channel>
8577 print "<title>$title</title>\n" .
8578 "<link>$alt_url</link>\n" .
8579 "<description>$descr</description>\n" .
8580 "<language>en</language>\n" .
8581 # project owner is responsible for 'editorial' content
8582 "<managingEditor>$owner</managingEditor>\n";
8583 if (defined $logo || defined $favicon) {
8584 # prefer the logo to the favicon, since RSS
8585 # doesn't allow both
8586 my $img = esc_url($logo || $favicon);
8587 print "<image>\n" .
8588 "<url>$img</url>\n" .
8589 "<title>$title</title>\n" .
8590 "<link>$alt_url</link>\n" .
8591 "</image>\n";
8593 if (%latest_date) {
8594 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
8595 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
8597 print "<generator>gitweb v.$version/$git_version</generator>\n";
8598 } elsif ($format eq 'atom') {
8599 print <<XML;
8600 <feed xmlns="http://www.w3.org/2005/Atom">
8602 print "<title>$title</title>\n" .
8603 "<subtitle>$descr</subtitle>\n" .
8604 '<link rel="alternate" type="text/html" href="' .
8605 $alt_url . '" />' . "\n" .
8606 '<link rel="self" type="' . $content_type . '" href="' .
8607 $cgi->self_url() . '" />' . "\n" .
8608 "<id>" . href(-full=>1) . "</id>\n" .
8609 # use project owner for feed author
8610 "<author><name>$owner</name></author>\n";
8611 if (defined $favicon) {
8612 print "<icon>" . esc_url($favicon) . "</icon>\n";
8614 if (defined $logo) {
8615 # not twice as wide as tall: 72 x 27 pixels
8616 print "<logo>" . esc_url($logo) . "</logo>\n";
8618 if (! %latest_date) {
8619 # dummy date to keep the feed valid until commits trickle in:
8620 print "<updated>1970-01-01T00:00:00Z</updated>\n";
8621 } else {
8622 print "<updated>$latest_date{'iso-8601'}</updated>\n";
8624 print "<generator version='$version/$git_version'>gitweb</generator>\n";
8627 # contents
8628 for (my $i = 0; $i <= $#commitlist; $i++) {
8629 my %co = %{$commitlist[$i]};
8630 my $commit = $co{'id'};
8631 # we read 150, we always show 30 and the ones more recent than 48 hours
8632 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
8633 last;
8635 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
8637 # get list of changed files
8638 defined(my $fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
8639 $co{'parent'} || "--root",
8640 $co{'id'}, "--", (defined $file_name ? $file_name : ()))
8641 or next;
8642 my @difftree = map { chomp; to_utf8($_) } <$fd>;
8643 close $fd
8644 or next;
8646 # print element (entry, item)
8647 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
8648 if ($format eq 'rss') {
8649 print "<item>\n" .
8650 "<title>" . esc_html($co{'title'}) . "</title>\n" .
8651 "<author>" . esc_html($co{'author'}) . "</author>\n" .
8652 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
8653 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
8654 "<link>$co_url</link>\n" .
8655 "<description>" . esc_html($co{'title'}) . "</description>\n" .
8656 "<content:encoded>" .
8657 "<![CDATA[\n";
8658 } elsif ($format eq 'atom') {
8659 print "<entry>\n" .
8660 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
8661 "<updated>$cd{'iso-8601'}</updated>\n" .
8662 "<author>\n" .
8663 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
8664 if ($co{'author_email'}) {
8665 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
8667 print "</author>\n" .
8668 # use committer for contributor
8669 "<contributor>\n" .
8670 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
8671 if ($co{'committer_email'}) {
8672 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
8674 print "</contributor>\n" .
8675 "<published>$cd{'iso-8601'}</published>\n" .
8676 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
8677 "<id>$co_url</id>\n" .
8678 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
8679 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
8681 my $comment = $co{'comment'};
8682 print "<pre>\n";
8683 foreach my $line (@$comment) {
8684 $line = esc_html($line);
8685 print "$line\n";
8687 print "</pre><ul>\n";
8688 foreach my $difftree_line (@difftree) {
8689 my %difftree = parse_difftree_raw_line($difftree_line);
8690 next if !$difftree{'from_id'};
8692 my $file = $difftree{'file'} || $difftree{'to_file'};
8694 print "<li>" .
8695 "[" .
8696 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
8697 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
8698 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
8699 file_name=>$file, file_parent=>$difftree{'from_file'}),
8700 -title => "diff"}, 'D');
8701 if ($have_blame) {
8702 print $cgi->a({-href => href(-full=>1, action=>"blame",
8703 file_name=>$file, hash_base=>$commit),
8704 -title => "blame"}, 'B');
8706 # if this is not a feed of a file history
8707 if (!defined $file_name || $file_name ne $file) {
8708 print $cgi->a({-href => href(-full=>1, action=>"history",
8709 file_name=>$file, hash=>$commit),
8710 -title => "history"}, 'H');
8712 $file = esc_path($file);
8713 print "] ".
8714 "$file</li>\n";
8716 if ($format eq 'rss') {
8717 print "</ul>]]>\n" .
8718 "</content:encoded>\n" .
8719 "</item>\n";
8720 } elsif ($format eq 'atom') {
8721 print "</ul>\n</div>\n" .
8722 "</content>\n" .
8723 "</entry>\n";
8727 # end of feed
8728 if ($format eq 'rss') {
8729 print "</channel>\n</rss>\n";
8730 } elsif ($format eq 'atom') {
8731 print "</feed>\n";
8735 sub git_rss {
8736 git_feed('rss');
8739 sub git_atom {
8740 git_feed('atom');
8743 sub git_opml {
8744 my @list = git_get_projects_list($project_filter, $strict_export);
8745 if (!@list) {
8746 die_error(404, "No projects found");
8749 print $cgi->header(
8750 -type => 'text/xml',
8751 -charset => 'utf-8',
8752 -content_disposition => 'inline; filename="opml.xml"');
8754 my $title = esc_html($site_name);
8755 my $filter = " within subdirectory ";
8756 if (defined $project_filter) {
8757 $filter .= esc_html($project_filter);
8758 } else {
8759 $filter = "";
8761 print <<XML;
8762 <?xml version="1.0" encoding="utf-8"?>
8763 <opml version="1.0">
8764 <head>
8765 <title>$title OPML Export$filter</title>
8766 </head>
8767 <body>
8768 <outline text="git RSS feeds">
8771 foreach my $pr (@list) {
8772 my %proj = %$pr;
8773 my $head = git_get_head_hash($proj{'path'});
8774 if (!defined $head) {
8775 next;
8777 $git_dir = "$projectroot/$proj{'path'}";
8778 my %co = parse_commit($head);
8779 if (!%co) {
8780 next;
8783 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
8784 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
8785 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
8786 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
8788 print <<XML;
8789 </outline>
8790 </body>
8791 </opml>