Merge branch 't/pending/updates' into refs/top-bases/gitweb-additions
[git/gitweb.git] / gitweb / gitweb.perl
blobadc91d0cd4fab1c81145d6311570c3c22e4bc539
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 use Time::Local;
23 use constant GITWEB_CACHE_FORMAT => "Gitweb Cache Format 3";
24 binmode STDOUT, ':utf8';
26 if (!defined($CGI::VERSION) || $CGI::VERSION < 4.08) {
27 eval 'sub CGI::multi_param { CGI::param(@_) }'
30 our $t0 = [ gettimeofday() ];
31 our $number_of_git_cmds = 0;
33 BEGIN {
34 CGI->compile() if $ENV{'MOD_PERL'};
37 our $version = "++GIT_VERSION++";
39 our ($my_url, $my_uri, $base_url, $path_info, $home_link);
40 sub evaluate_uri {
41 our $cgi;
43 our $my_url = $cgi->url();
44 our $my_uri = $cgi->url(-absolute => 1);
46 # Base URL for relative URLs in gitweb ($logo, $favicon, ...),
47 # needed and used only for URLs with nonempty PATH_INFO
48 # This must be an absolute URL (i.e. no scheme, host or port), NOT a full one
49 our $base_url = $my_uri || '/';
51 # When the script is used as DirectoryIndex, the URL does not contain the name
52 # of the script file itself, and $cgi->url() fails to strip PATH_INFO, so we
53 # have to do it ourselves. We make $path_info global because it's also used
54 # later on.
56 # Another issue with the script being the DirectoryIndex is that the resulting
57 # $my_url data is not the full script URL: this is good, because we want
58 # generated links to keep implying the script name if it wasn't explicitly
59 # indicated in the URL we're handling, but it means that $my_url cannot be used
60 # as base URL.
61 # Therefore, if we needed to strip PATH_INFO, then we know that we have
62 # to build the base URL ourselves:
63 our $path_info = decode_utf8($ENV{"PATH_INFO"});
64 if ($path_info) {
65 # $path_info has already been URL-decoded by the web server, but
66 # $my_url and $my_uri have not. URL-decode them so we can properly
67 # strip $path_info.
68 $my_url = unescape($my_url);
69 $my_uri = unescape($my_uri);
70 if ($my_url =~ s,\Q$path_info\E$,, &&
71 $my_uri =~ s,\Q$path_info\E$,, &&
72 defined $ENV{'SCRIPT_NAME'}) {
73 $base_url = $ENV{'SCRIPT_NAME'} || '/';
77 # target of the home link on top of all pages
78 our $home_link = $my_uri || "/";
81 # core git executable to use
82 # this can just be "git" if your webserver has a sensible PATH
83 our $GIT = "++GIT_BINDIR++/git";
85 # absolute fs-path which will be prepended to the project path
86 #our $projectroot = "/pub/scm";
87 our $projectroot = "++GITWEB_PROJECTROOT++";
89 # fs traversing limit for getting project list
90 # the number is relative to the projectroot
91 our $project_maxdepth = "++GITWEB_PROJECT_MAXDEPTH++";
93 # string of the home link on top of all pages
94 our $home_link_str = "++GITWEB_HOME_LINK_STR++";
96 # extra breadcrumbs preceding the home link
97 our @extra_breadcrumbs = ();
99 # name of your site or organization to appear in page titles
100 # replace this with something more descriptive for clearer bookmarks
101 our $site_name = "++GITWEB_SITENAME++"
102 || ($ENV{'SERVER_NAME'} || "Untitled") . " Git";
104 # html snippet to include in the <head> section of each page
105 our $site_html_head_string = "++GITWEB_SITE_HTML_HEAD_STRING++";
106 # filename of html text to include at top of each page
107 our $site_header = "++GITWEB_SITE_HEADER++";
108 # html text to include at home page
109 our $home_text = "++GITWEB_HOMETEXT++";
110 # filename of html text to include at bottom of each page
111 our $site_footer = "++GITWEB_SITE_FOOTER++";
113 # URI of stylesheets
114 our @stylesheets = ("++GITWEB_CSS++");
115 # URI of a single stylesheet, which can be overridden in GITWEB_CONFIG.
116 our $stylesheet = undef;
117 # URI of GIT logo (72x27 size)
118 our $logo = "++GITWEB_LOGO++";
119 # URI of GIT favicon, assumed to be image/png type
120 our $favicon = "++GITWEB_FAVICON++";
121 # URI of gitweb.js (JavaScript code for gitweb)
122 our $javascript = "++GITWEB_JS++";
124 # URI and label (title) of GIT logo link
125 #our $logo_url = "http://www.kernel.org/pub/software/scm/git/docs/";
126 #our $logo_label = "git documentation";
127 our $logo_url = "http://git-scm.com/";
128 our $logo_label = "git homepage";
130 # source of projects list
131 our $projects_list = "++GITWEB_LIST++";
133 # the width (in characters) of the projects list "Description" column
134 our $projects_list_description_width = 25;
136 # group projects by category on the projects list
137 # (enabled if this variable evaluates to true)
138 our $projects_list_group_categories = 0;
140 # default category if none specified
141 # (leave the empty string for no category)
142 our $project_list_default_category = "";
144 # default order of projects list
145 # valid values are none, project, descr, owner, and age
146 our $default_projects_order = "project";
148 # default order of refs list
149 # valid values are age and name
150 our $default_refs_order = "age";
152 # show repository only if this file exists
153 # (only effective if this variable evaluates to true)
154 our $export_ok = "++GITWEB_EXPORT_OK++";
156 # don't generate age column on the projects list page
157 our $omit_age_column = 0;
159 # use contents of this file (in iso, iso-strict or raw format) as
160 # the last activity data if it exists and is a valid date
161 our $lastactivity_file = undef;
163 # don't generate information about owners of repositories
164 our $omit_owner=0;
166 # owner link hook given owner name (full and NOT obfuscated)
167 # should return full URL-escaped link to attach to owner, for example:
168 # sub { return "/showowner.cgi?owner=".CGI::Util::escape($_[0]); }
169 our $owner_link_hook = undef;
171 # show repository only if this subroutine returns true
172 # when given the path to the project, for example:
173 # sub { return -e "$_[0]/git-daemon-export-ok"; }
174 our $export_auth_hook = undef;
176 # only allow viewing of repositories also shown on the overview page
177 our $strict_export = "++GITWEB_STRICT_EXPORT++";
179 # list of git base URLs used for URL to where fetch project from,
180 # i.e. full URL is "$git_base_url/$project"
181 our @git_base_url_list = grep { $_ ne '' } ("++GITWEB_BASE_URL++");
183 # URLs designated for pushing new changes, extended by the
184 # project name (i.e. "$git_base_push_url[0]/$project")
185 our @git_base_push_urls = ();
187 # https hint html inserted right after any https push URL (undef for none)
188 our $https_hint_html = undef;
190 # default blob_plain mimetype and default charset for text/plain blob
191 our $default_blob_plain_mimetype = 'application/octet-stream';
192 our $default_text_plain_charset = undef;
194 # file to use for guessing MIME types before trying /etc/mime.types
195 # (relative to the current git repository)
196 our $mimetypes_file = undef;
198 # assume this charset if line contains non-UTF-8 characters;
199 # it should be valid encoding (see Encoding::Supported(3pm) for list),
200 # for which encoding all byte sequences are valid, for example
201 # 'iso-8859-1' aka 'latin1' (it is decoded without checking, so it
202 # could be even 'utf-8' for the old behavior)
203 our $fallback_encoding = 'latin1';
205 # rename detection options for git-diff and git-diff-tree
206 # - default is '-M', with the cost proportional to
207 # (number of removed files) * (number of new files).
208 # - more costly is '-C' (which implies '-M'), with the cost proportional to
209 # (number of changed files + number of removed files) * (number of new files)
210 # - even more costly is '-C', '--find-copies-harder' with cost
211 # (number of files in the original tree) * (number of new files)
212 # - one might want to include '-B' option, e.g. '-B', '-M'
213 our @diff_opts = ('-M'); # taken from git_commit
215 # cache directory (relative to $GIT_DIR) for project-specific html page caches.
216 # the directory must exist and be writable by the process running gitweb.
217 # additionally some actions must be selected for caching in %html_cache_actions
218 # - default is 'htmlcache'
219 our $html_cache_dir = 'htmlcache';
221 # which actions to cache in $html_cache_dir
222 # if $html_cache_dir exists (relative to $GIT_DIR) and is writable by the
223 # process running gitweb, then any actions selected here will have their output
224 # cached and the cache file will be returned instead of regenerating the page
225 # if it exists. For this to be useful, an external process must create the
226 # 'changed' file (if it does not already exist) in the $html_cache_dir whenever
227 # the project information has been changed. Alternatively it may create a
228 # "$action.changed" file (if it does not exist) instead to limit the changes
229 # to just "$action" instead of any action. If 'changed' or "$action.changed"
230 # exist, then the cached version will never be used for "$action" and a new
231 # cache page will be regenerated (and the "changed" files removed as appropriate).
233 # Additionally if $projlist_cache_lifetime is > 0 AND the forks feature has been
234 # enabled ('$feature{'forks'}{'default'} = [1];') then additionally an external
235 # process must create the 'forkchange' file or update its timestamp if it already
236 # exists whenever a fork is added to or removed from the project (as well as
237 # create the 'changed' or "$action.changed" file). Otherwise the "forks"
238 # section on the summary page may remain out-of-date indefinately.
240 # - default is none
241 # currently only caching of the summary page is supported
242 # - to enable caching of the summary page use:
243 # $html_cache_actions{'summary'} = 1;
244 our %html_cache_actions = ();
246 # Disables features that would allow repository owners to inject script into
247 # the gitweb domain.
248 our $prevent_xss = 0;
250 # Path to a POSIX shell. Needed to run $highlight_bin and a snapshot compressor.
251 # Only used when highlight is enabled or snapshots with compressors are enabled.
252 our $posix_shell_bin = "++POSIX_SHELL_BIN++";
254 # Path to the highlight executable to use (must be the one from
255 # http://www.andre-simon.de due to assumptions about parameters and output).
256 # Useful if highlight is not installed on your webserver's PATH.
257 # [Default: highlight]
258 our $highlight_bin = "++HIGHLIGHT_BIN++";
260 # Whether to include project list on the gitweb front page; 0 means yes,
261 # 1 means no list but show tag cloud if enabled (all projects still need
262 # to be scanned, unless the info is cached), 2 means no list and no tag cloud
263 # (very fast)
264 our $frontpage_no_project_list = 0;
266 # projects list cache for busy sites with many projects;
267 # if you set this to non-zero, it will be used as the cached
268 # index lifetime in minutes
270 # the cached list version is stored in $cache_dir/$cache_name and can
271 # be tweaked by other scripts running with the same uid as gitweb -
272 # use this ONLY at secure installations; only single gitweb project
273 # root per system is supported, unless you tweak configuration!
274 our $projlist_cache_lifetime = 0; # in minutes
275 # FHS compliant $cache_dir would be "/var/cache/gitweb"
276 our $cache_dir =
277 (defined $ENV{'TMPDIR'} ? $ENV{'TMPDIR'} : '/tmp').'/gitweb';
278 our $projlist_cache_name = 'gitweb.index.cache';
279 our $cache_grpshared = 0;
281 # information about snapshot formats that gitweb is capable of serving
282 our %known_snapshot_formats = (
283 # name => {
284 # 'display' => display name,
285 # 'type' => mime type,
286 # 'suffix' => filename suffix,
287 # 'format' => --format for git-archive,
288 # 'compressor' => [compressor command and arguments]
289 # (array reference, optional)
290 # 'disabled' => boolean (optional)}
292 'tgz' => {
293 'display' => 'tar.gz',
294 'type' => 'application/x-gzip',
295 'suffix' => '.tar.gz',
296 'format' => 'tar',
297 'compressor' => ['gzip', '-n']},
299 'tbz2' => {
300 'display' => 'tar.bz2',
301 'type' => 'application/x-bzip2',
302 'suffix' => '.tar.bz2',
303 'format' => 'tar',
304 'compressor' => ['bzip2']},
306 'txz' => {
307 'display' => 'tar.xz',
308 'type' => 'application/x-xz',
309 'suffix' => '.tar.xz',
310 'format' => 'tar',
311 'compressor' => ['xz'],
312 'disabled' => 1},
314 'zip' => {
315 'display' => 'zip',
316 'type' => 'application/x-zip',
317 'suffix' => '.zip',
318 'format' => 'zip'},
321 # Aliases so we understand old gitweb.snapshot values in repository
322 # configuration.
323 our %known_snapshot_format_aliases = (
324 'gzip' => 'tgz',
325 'bzip2' => 'tbz2',
326 'xz' => 'txz',
328 # backward compatibility: legacy gitweb config support
329 'x-gzip' => undef, 'gz' => undef,
330 'x-bzip2' => undef, 'bz2' => undef,
331 'x-zip' => undef, '' => undef,
334 # Pixel sizes for icons and avatars. If the default font sizes or lineheights
335 # are changed, it may be appropriate to change these values too via
336 # $GITWEB_CONFIG.
337 our %avatar_size = (
338 'default' => 16,
339 'double' => 32
342 # Used to set the maximum load that we will still respond to gitweb queries.
343 # If server load exceed this value then return "503 server busy" error.
344 # If gitweb cannot determined server load, it is taken to be 0.
345 # Leave it undefined (or set to 'undef') to turn off load checking.
346 our $maxload = 300;
348 # configuration for 'highlight' (http://www.andre-simon.de/)
349 # match by basename
350 our %highlight_basename = (
351 #'Program' => 'py',
352 #'Library' => 'py',
353 'SConstruct' => 'py', # SCons equivalent of Makefile
354 'Makefile' => 'make',
355 'makefile' => 'make',
356 'GNUmakefile' => 'make',
357 'BSDmakefile' => 'make',
359 # match by shebang regex
360 our %highlight_shebang = (
361 # Each entry has a key which is the syntax to use and
362 # a value which is either a qr regex or an array of qr regexs to match
363 # against the first 128 (less if the blob is shorter) BYTES of the blob.
364 # We match /usr/bin/env items separately to require "/usr/bin/env" and
365 # allow a limited subset of NAME=value items to appear.
366 'awk' => [ qr,^#!\s*/(?:\w+/)*(?:[gnm]?awk)(?:\s|$),mo,
367 qr,^#!\s*/usr/bin/env\s+(?:\w+=\w*\s+)*(?:[gnm]?awk)(?:\s|$),mo ],
368 'make' => [ qr,^#!\s*/(?:\w+/)*(?:g?make)(?:\s|$),mo,
369 qr,^#!\s*/usr/bin/env\s+(?:\w+=\w*\s+)*(?:g?make)(?:\s|$),mo ],
370 'php' => [ qr,^#!\s*/(?:\w+/)*(?:php)(?:\s|$),mo,
371 qr,^#!\s*/usr/bin/env\s+(?:\w+=\w*\s+)*(?:php)(?:\s|$),mo ],
372 'pl' => [ qr,^#!\s*/(?:\w+/)*(?:perl)(?:\s|$),mo,
373 qr,^#!\s*/usr/bin/env\s+(?:\w+=\w*\s+)*(?:perl)(?:\s|$),mo ],
374 'py' => [ qr,^#!\s*/(?:\w+/)*(?:python)(?:\s|$),mo,
375 qr,^#!\s*/usr/bin/env\s+(?:\w+=\w*\s+)*(?:python)(?:\s|$),mo ],
376 'sh' => [ qr,^#!\s*/(?:\w+/)*(?:[bd]ash|t?csh|[akz]?sh)(?:\s|$),mo,
377 qr,^#!\s*/usr/bin/env\s+(?:\w+=\w*\s+)*(?:[bd]ash|t?csh|[akz]?sh)(?:\s|$),mo ],
378 'rb' => [ qr,^#!\s*/(?:\w+/)*(?:perl)(?:\s|$),mo,
379 qr,^#!\s*/usr/bin/env\s+(?:\w+=\w*\s+)*(?:perl)(?:\s|$),mo ],
381 # match by extension
382 our %highlight_ext = (
383 # main extensions, defining name of syntax;
384 # see files in /usr/share/highlight/langDefs/ directory
385 (map { $_ => $_ } qw(
386 4gl a4c abnf abp ada agda ahk ampl amtrix applescript arc
387 arm as asm asp aspect ats au3 avenue awk bat bb bbcode bib
388 bms bnf boo c cb cfc chl clipper clojure clp cob cs css d
389 diff dot dylan e ebnf erl euphoria exp f90 flx for frink fs
390 go haskell hcl html httpd hx icl icn idl idlang ili
391 inc_luatex ini inp io iss j java js jsp lbn ldif lgt lhs
392 lisp lotos ls lsl lua ly make mel mercury mib miranda ml mo
393 mod2 mod3 mpl ms mssql n nas nbc nice nrx nsi nut nxc oberon
394 objc octave oorexx os oz pas php pike pl pl1 pov pro
395 progress ps ps1 psl pure py pyx q qmake qu r rb rebol rexx
396 rnc s sas sc scala scilab sh sma smalltalk sml sno spec spn
397 sql sybase tcl tcsh tex ttcn3 vala vb verilog vhd xml xpp y
398 yaiff znn)),
399 # alternate extensions, see /etc/highlight/filetypes.conf
400 (map { $_ => '4gl' } qw(informix)),
401 (map { $_ => 'a4c' } qw(ascend)),
402 (map { $_ => 'abp' } qw(abp4)),
403 (map { $_ => 'ada' } qw(a adb ads gnad)),
404 (map { $_ => 'ahk' } qw(autohotkey)),
405 (map { $_ => 'ampl' } qw(dat run)),
406 (map { $_ => 'amtrix' } qw(hnd s4 s4h s4t t4)),
407 (map { $_ => 'as' } qw(actionscript)),
408 (map { $_ => 'asm' } qw(29k 68s 68x a51 assembler x68 x86)),
409 (map { $_ => 'asp' } qw(asa)),
410 (map { $_ => 'aspect' } qw(was wud)),
411 (map { $_ => 'ats' } qw(dats)),
412 (map { $_ => 'au3' } qw(autoit)),
413 (map { $_ => 'bat' } qw(cmd)),
414 (map { $_ => 'bb' } qw(blitzbasic)),
415 (map { $_ => 'bib' } qw(bibtex)),
416 (map { $_ => 'c' } qw(c++ cc cpp cu cxx h hh hpp hxx)),
417 (map { $_ => 'cb' } qw(clearbasic)),
418 (map { $_ => 'cfc' } qw(cfm coldfusion)),
419 (map { $_ => 'chl' } qw(chill)),
420 (map { $_ => 'cob' } qw(cbl cobol)),
421 (map { $_ => 'cs' } qw(csharp)),
422 (map { $_ => 'diff' } qw(patch)),
423 (map { $_ => 'dot' } qw(graphviz)),
424 (map { $_ => 'e' } qw(eiffel se)),
425 (map { $_ => 'erl' } qw(erlang hrl)),
426 (map { $_ => 'euphoria' } qw(eu ew ex exu exw wxu)),
427 (map { $_ => 'exp' } qw(express)),
428 (map { $_ => 'f90' } qw(f95)),
429 (map { $_ => 'flx' } qw(felix)),
430 (map { $_ => 'for' } qw(f f77 ftn)),
431 (map { $_ => 'fs' } qw(fsharp fsx)),
432 (map { $_ => 'haskell' } qw(hs)),
433 (map { $_ => 'html' } qw(htm xhtml)),
434 (map { $_ => 'hx' } qw(haxe)),
435 (map { $_ => 'icl' } qw(clean)),
436 (map { $_ => 'icn' } qw(icon)),
437 (map { $_ => 'ili' } qw(interlis)),
438 (map { $_ => 'inp' } qw(fame)),
439 (map { $_ => 'iss' } qw(innosetup)),
440 (map { $_ => 'j' } qw(jasmin)),
441 (map { $_ => 'java' } qw(groovy grv)),
442 (map { $_ => 'lbn' } qw(luban)),
443 (map { $_ => 'lgt' } qw(logtalk)),
444 (map { $_ => 'lisp' } qw(cl clisp el lsp sbcl scom)),
445 (map { $_ => 'ls' } qw(lotus)),
446 (map { $_ => 'lsl' } qw(lindenscript)),
447 (map { $_ => 'ly' } qw(lilypond)),
448 (map { $_ => 'make' } qw(mak mk kmk)),
449 (map { $_ => 'mel' } qw(maya)),
450 (map { $_ => 'mib' } qw(smi snmp)),
451 (map { $_ => 'ml' } qw(mli ocaml)),
452 (map { $_ => 'mo' } qw(modelica)),
453 (map { $_ => 'mod2' } qw(def mod)),
454 (map { $_ => 'mod3' } qw(i3 m3)),
455 (map { $_ => 'mpl' } qw(maple)),
456 (map { $_ => 'n' } qw(nemerle)),
457 (map { $_ => 'nas' } qw(nasal)),
458 (map { $_ => 'nrx' } qw(netrexx)),
459 (map { $_ => 'nsi' } qw(nsis)),
460 (map { $_ => 'nut' } qw(squirrel)),
461 (map { $_ => 'oberon' } qw(ooc)),
462 (map { $_ => 'objc' } qw(M m mm)),
463 (map { $_ => 'php' } qw(php3 php4 php5 php6)),
464 (map { $_ => 'pike' } qw(pmod)),
465 (map { $_ => 'pl' } qw(perl plex plx pm)),
466 (map { $_ => 'pl1' } qw(bdy ff fp fpp rpp sf sp spb spe spp sps wf wp wpb wpp wps)),
467 (map { $_ => 'progress' } qw(i p w)),
468 (map { $_ => 'py' } qw(python)),
469 (map { $_ => 'pyx' } qw(pyrex)),
470 (map { $_ => 'rb' } qw(pp rjs ruby)),
471 (map { $_ => 'rexx' } qw(rex rx the)),
472 (map { $_ => 'sc' } qw(paradox)),
473 (map { $_ => 'scilab' } qw(sce sci)),
474 (map { $_ => 'sh' } qw(bash ebuild eclass ksh zsh)),
475 (map { $_ => 'sma' } qw(small)),
476 (map { $_ => 'smalltalk' } qw(gst sq st)),
477 (map { $_ => 'sno' } qw(snobal)),
478 (map { $_ => 'sybase' } qw(sp)),
479 (map { $_ => 'tcl' } qw(itcl wish)),
480 (map { $_ => 'tex' } qw(cls sty)),
481 (map { $_ => 'vb' } qw(bas basic bi vbs)),
482 (map { $_ => 'verilog' } qw(v)),
483 (map { $_ => 'xml' } qw(dtd ecf ent hdr hub jnlp nrm plist resx sgm sgml svg tld vxml wml xsd xsl)),
484 (map { $_ => 'y' } qw(bison)),
487 # You define site-wide feature defaults here; override them with
488 # $GITWEB_CONFIG as necessary.
489 our %feature = (
490 # feature => {
491 # 'sub' => feature-sub (subroutine),
492 # 'override' => allow-override (boolean),
493 # 'default' => [ default options...] (array reference)}
495 # if feature is overridable (it means that allow-override has true value),
496 # then feature-sub will be called with default options as parameters;
497 # return value of feature-sub indicates if to enable specified feature
499 # if there is no 'sub' key (no feature-sub), then feature cannot be
500 # overridden
502 # use gitweb_get_feature(<feature>) to retrieve the <feature> value
503 # (an array) or gitweb_check_feature(<feature>) to check if <feature>
504 # is enabled
506 # Enable the 'blame' blob view, showing the last commit that modified
507 # each line in the file. This can be very CPU-intensive.
509 # To enable system wide have in $GITWEB_CONFIG
510 # $feature{'blame'}{'default'} = [1];
511 # To have project specific config enable override in $GITWEB_CONFIG
512 # $feature{'blame'}{'override'} = 1;
513 # and in project config gitweb.blame = 0|1;
514 'blame' => {
515 'sub' => sub { feature_bool('blame', @_) },
516 'override' => 0,
517 'default' => [0]},
519 # Enable the 'incremental blame' blob view, which uses javascript to
520 # incrementally show the revisions of lines as they are discovered
521 # in the history. It is better for large histories, files and slow
522 # servers, but requires javascript in the client and can slow down the
523 # browser on large files.
525 # To enable system wide have in $GITWEB_CONFIG
526 # $feature{'blame_incremental'}{'default'} = [1];
527 # To have project specific config enable override in $GITWEB_CONFIG
528 # $feature{'blame_incremental'}{'override'} = 1;
529 # and in project config gitweb.blame_incremental = 0|1;
530 'blame_incremental' => {
531 'sub' => sub { feature_bool('blame_incremental', @_) },
532 'override' => 0,
533 'default' => [0]},
535 # Enable the 'snapshot' link, providing a compressed archive of any
536 # tree. This can potentially generate high traffic if you have large
537 # project.
539 # Value is a list of formats defined in %known_snapshot_formats that
540 # you wish to offer.
541 # To disable system wide have in $GITWEB_CONFIG
542 # $feature{'snapshot'}{'default'} = [];
543 # To have project specific config enable override in $GITWEB_CONFIG
544 # $feature{'snapshot'}{'override'} = 1;
545 # and in project config, a comma-separated list of formats or "none"
546 # to disable. Example: gitweb.snapshot = tbz2,zip;
547 'snapshot' => {
548 'sub' => \&feature_snapshot,
549 'override' => 0,
550 'default' => ['tgz']},
552 # Enable text search, which will list the commits which match author,
553 # committer or commit text to a given string. Enabled by default.
554 # Project specific override is not supported.
556 # Note that this controls all search features, which means that if
557 # it is disabled, then 'grep' and 'pickaxe' search would also be
558 # disabled.
559 'search' => {
560 'override' => 0,
561 'default' => [1]},
563 # Enable grep search, which will list the files in currently selected
564 # tree containing the given string. Enabled by default. This can be
565 # potentially CPU-intensive, of course.
566 # Note that you need to have 'search' feature enabled too.
568 # To enable system wide have in $GITWEB_CONFIG
569 # $feature{'grep'}{'default'} = [1];
570 # To have project specific config enable override in $GITWEB_CONFIG
571 # $feature{'grep'}{'override'} = 1;
572 # and in project config gitweb.grep = 0|1;
573 'grep' => {
574 'sub' => sub { feature_bool('grep', @_) },
575 'override' => 0,
576 'default' => [1]},
578 # Enable the pickaxe search, which will list the commits that modified
579 # a given string in a file. This can be practical and quite faster
580 # alternative to 'blame', but still potentially CPU-intensive.
581 # Note that you need to have 'search' feature enabled too.
583 # To enable system wide have in $GITWEB_CONFIG
584 # $feature{'pickaxe'}{'default'} = [1];
585 # To have project specific config enable override in $GITWEB_CONFIG
586 # $feature{'pickaxe'}{'override'} = 1;
587 # and in project config gitweb.pickaxe = 0|1;
588 'pickaxe' => {
589 'sub' => sub { feature_bool('pickaxe', @_) },
590 'override' => 0,
591 'default' => [1]},
593 # Enable showing size of blobs in a 'tree' view, in a separate
594 # column, similar to what 'ls -l' does. This cost a bit of IO.
596 # To disable system wide have in $GITWEB_CONFIG
597 # $feature{'show-sizes'}{'default'} = [0];
598 # To have project specific config enable override in $GITWEB_CONFIG
599 # $feature{'show-sizes'}{'override'} = 1;
600 # and in project config gitweb.showsizes = 0|1;
601 'show-sizes' => {
602 'sub' => sub { feature_bool('showsizes', @_) },
603 'override' => 0,
604 'default' => [1]},
606 # Make gitweb use an alternative format of the URLs which can be
607 # more readable and natural-looking: project name is embedded
608 # directly in the path and the query string contains other
609 # auxiliary information. All gitweb installations recognize
610 # URL in either format; this configures in which formats gitweb
611 # generates links.
613 # To enable system wide have in $GITWEB_CONFIG
614 # $feature{'pathinfo'}{'default'} = [1];
615 # Project specific override is not supported.
617 # Note that you will need to change the default location of CSS,
618 # favicon, logo and possibly other files to an absolute URL. Also,
619 # if gitweb.cgi serves as your indexfile, you will need to force
620 # $my_uri to contain the script name in your $GITWEB_CONFIG (and you
621 # will also likely want to set $home_link if you're setting $my_uri).
622 'pathinfo' => {
623 'override' => 0,
624 'default' => [0]},
626 # Make gitweb consider projects in project root subdirectories
627 # to be forks of existing projects. Given project $projname.git,
628 # projects matching $projname/*.git will not be shown in the main
629 # projects list, instead a '+' mark will be added to $projname
630 # there and a 'forks' view will be enabled for the project, listing
631 # all the forks. If project list is taken from a file, forks have
632 # to be listed after the main project.
634 # To enable system wide have in $GITWEB_CONFIG
635 # $feature{'forks'}{'default'} = [1];
636 # Project specific override is not supported.
637 'forks' => {
638 'override' => 0,
639 'default' => [0]},
641 # Insert custom links to the action bar of all project pages.
642 # This enables you mainly to link to third-party scripts integrating
643 # into gitweb; e.g. git-browser for graphical history representation
644 # or custom web-based repository administration interface.
646 # The 'default' value consists of a list of triplets in the form
647 # (label, link, position) where position is the label after which
648 # to insert the link and link is a format string where %n expands
649 # to the project name, %f to the project path within the filesystem,
650 # %h to the current hash (h gitweb parameter) and %b to the current
651 # hash base (hb gitweb parameter); %% expands to %. %e expands to the
652 # project name where all '+' characters have been replaced with '%2B'.
654 # To enable system wide have in $GITWEB_CONFIG e.g.
655 # $feature{'actions'}{'default'} = [('graphiclog',
656 # '/git-browser/by-commit.html?r=%n', 'summary')];
657 # Project specific override is not supported.
658 'actions' => {
659 'override' => 0,
660 'default' => []},
662 # Allow gitweb scan project content tags of project repository,
663 # and display the popular Web 2.0-ish "tag cloud" near the projects
664 # list. Note that this is something COMPLETELY different from the
665 # normal Git tags.
667 # gitweb by itself can show existing tags, but it does not handle
668 # tagging itself; you need to do it externally, outside gitweb.
669 # The format is described in git_get_project_ctags() subroutine.
670 # You may want to install the HTML::TagCloud Perl module to get
671 # a pretty tag cloud instead of just a list of tags.
673 # To enable system wide have in $GITWEB_CONFIG
674 # $feature{'ctags'}{'default'} = [1];
675 # Project specific override is not supported.
677 # A value of 0 means no ctags display or editing. A value of
678 # 1 enables ctags display but never editing. A non-empty value
679 # that is not a string of digits enables ctags display AND the
680 # ability to add tags using a form that uses method POST and
681 # an action value set to the configured 'ctags' value.
682 'ctags' => {
683 'override' => 0,
684 'default' => [0]},
686 # The maximum number of patches in a patchset generated in patch
687 # view. Set this to 0 or undef to disable patch view, or to a
688 # negative number to remove any limit.
690 # To disable system wide have in $GITWEB_CONFIG
691 # $feature{'patches'}{'default'} = [0];
692 # To have project specific config enable override in $GITWEB_CONFIG
693 # $feature{'patches'}{'override'} = 1;
694 # and in project config gitweb.patches = 0|n;
695 # where n is the maximum number of patches allowed in a patchset.
696 'patches' => {
697 'sub' => \&feature_patches,
698 'override' => 0,
699 'default' => [16]},
701 # Avatar support. When this feature is enabled, views such as
702 # shortlog or commit will display an avatar associated with
703 # the email of the committer(s) and/or author(s).
705 # Currently available providers are gravatar and picon.
706 # If an unknown provider is specified, the feature is disabled.
708 # Gravatar depends on Digest::MD5.
709 # Picon currently relies on the indiana.edu database.
711 # To enable system wide have in $GITWEB_CONFIG
712 # $feature{'avatar'}{'default'} = ['<provider>'];
713 # where <provider> is either gravatar or picon.
714 # To have project specific config enable override in $GITWEB_CONFIG
715 # $feature{'avatar'}{'override'} = 1;
716 # and in project config gitweb.avatar = <provider>;
717 'avatar' => {
718 'sub' => \&feature_avatar,
719 'override' => 0,
720 'default' => ['']},
722 # Enable displaying how much time and how many git commands
723 # it took to generate and display page. Disabled by default.
724 # Project specific override is not supported.
725 'timed' => {
726 'override' => 0,
727 'default' => [0]},
729 # Enable turning some links into links to actions which require
730 # JavaScript to run (like 'blame_incremental'). Not enabled by
731 # default. Project specific override is currently not supported.
732 'javascript-actions' => {
733 'override' => 0,
734 'default' => [0]},
736 # Enable and configure ability to change common timezone for dates
737 # in gitweb output via JavaScript. Enabled by default.
738 # Project specific override is not supported.
739 'javascript-timezone' => {
740 'override' => 0,
741 'default' => [
742 'local', # default timezone: 'utc', 'local', or '(-|+)HHMM' format,
743 # or undef to turn off this feature
744 'gitweb_tz', # name of cookie where to store selected timezone
745 'datetime', # CSS class used to mark up dates for manipulation
748 # Syntax highlighting support. This is based on Daniel Svensson's
749 # and Sham Chukoury's work in gitweb-xmms2.git.
750 # It requires the 'highlight' program present in $PATH,
751 # and therefore is disabled by default.
753 # To enable system wide have in $GITWEB_CONFIG
754 # $feature{'highlight'}{'default'} = [1];
756 'highlight' => {
757 'sub' => sub { feature_bool('highlight', @_) },
758 'override' => 0,
759 'default' => [0]},
761 # Enable displaying of remote heads in the heads list
763 # To enable system wide have in $GITWEB_CONFIG
764 # $feature{'remote_heads'}{'default'} = [1];
765 # To have project specific config enable override in $GITWEB_CONFIG
766 # $feature{'remote_heads'}{'override'} = 1;
767 # and in project config gitweb.remoteheads = 0|1;
768 'remote_heads' => {
769 'sub' => sub { feature_bool('remote_heads', @_) },
770 'override' => 0,
771 'default' => [0]},
773 # Enable showing branches under other refs in addition to heads
775 # To set system wide extra branch refs have in $GITWEB_CONFIG
776 # $feature{'extra-branch-refs'}{'default'} = ['dirs', 'of', 'choice'];
777 # To have project specific config enable override in $GITWEB_CONFIG
778 # $feature{'extra-branch-refs'}{'override'} = 1;
779 # and in project config gitweb.extrabranchrefs = dirs of choice
780 # Every directory is separated with whitespace.
782 'extra-branch-refs' => {
783 'sub' => \&feature_extra_branch_refs,
784 'override' => 0,
785 'default' => []},
788 sub gitweb_get_feature {
789 my ($name) = @_;
790 return unless exists $feature{$name};
791 my ($sub, $override, @defaults) = (
792 $feature{$name}{'sub'},
793 $feature{$name}{'override'},
794 @{$feature{$name}{'default'}});
795 # project specific override is possible only if we have project
796 our $git_dir; # global variable, declared later
797 if (!$override || !defined $git_dir) {
798 return @defaults;
800 if (!defined $sub) {
801 warn "feature $name is not overridable";
802 return @defaults;
804 return $sub->(@defaults);
807 # A wrapper to check if a given feature is enabled.
808 # With this, you can say
810 # my $bool_feat = gitweb_check_feature('bool_feat');
811 # gitweb_check_feature('bool_feat') or somecode;
813 # instead of
815 # my ($bool_feat) = gitweb_get_feature('bool_feat');
816 # (gitweb_get_feature('bool_feat'))[0] or somecode;
818 sub gitweb_check_feature {
819 return (gitweb_get_feature(@_))[0];
823 sub feature_bool {
824 my $key = shift;
825 my ($val) = git_get_project_config($key, '--bool');
827 if (!defined $val) {
828 return ($_[0]);
829 } elsif ($val eq 'true') {
830 return (1);
831 } elsif ($val eq 'false') {
832 return (0);
836 sub feature_snapshot {
837 my (@fmts) = @_;
839 my ($val) = git_get_project_config('snapshot');
841 if ($val) {
842 @fmts = ($val eq 'none' ? () : split /\s*[,\s]\s*/, $val);
845 return @fmts;
848 sub feature_patches {
849 my @val = (git_get_project_config('patches', '--int'));
851 if (@val) {
852 return @val;
855 return ($_[0]);
858 sub feature_avatar {
859 my @val = (git_get_project_config('avatar'));
861 return @val ? @val : @_;
864 sub feature_extra_branch_refs {
865 my (@branch_refs) = @_;
866 my $values = git_get_project_config('extrabranchrefs');
868 if ($values) {
869 $values = config_to_multi ($values);
870 @branch_refs = ();
871 foreach my $value (@{$values}) {
872 push @branch_refs, split /\s+/, $value;
876 return @branch_refs;
879 # checking HEAD file with -e is fragile if the repository was
880 # initialized long time ago (i.e. symlink HEAD) and was pack-ref'ed
881 # and then pruned.
882 sub check_head_link {
883 my ($dir) = @_;
884 return 0 unless -d "$dir/objects" && -x _;
885 return 0 unless -d "$dir/refs" && -x _;
886 my $headfile = "$dir/HEAD";
887 return -l $headfile ?
888 readlink($headfile) =~ /^refs\/heads\// : -f $headfile;
891 sub check_export_ok {
892 my ($dir) = @_;
893 return (check_head_link($dir) &&
894 (!$export_ok || -e "$dir/$export_ok") &&
895 (!$export_auth_hook || $export_auth_hook->($dir)));
898 # process alternate names for backward compatibility
899 # filter out unsupported (unknown) snapshot formats
900 sub filter_snapshot_fmts {
901 my @fmts = @_;
903 @fmts = map {
904 exists $known_snapshot_format_aliases{$_} ?
905 $known_snapshot_format_aliases{$_} : $_} @fmts;
906 @fmts = grep {
907 exists $known_snapshot_formats{$_} &&
908 !$known_snapshot_formats{$_}{'disabled'}} @fmts;
911 sub filter_and_validate_refs {
912 my @refs = @_;
913 my %unique_refs = ();
915 foreach my $ref (@refs) {
916 die_error(500, "Invalid ref '$ref' in 'extra-branch-refs' feature") unless (is_valid_ref_format($ref));
917 # 'heads' are added implicitly in get_branch_refs().
918 $unique_refs{$ref} = 1 if ($ref ne 'heads');
920 return sort keys %unique_refs;
923 # If it is set to code reference, it is code that it is to be run once per
924 # request, allowing updating configurations that change with each request,
925 # while running other code in config file only once.
927 # Otherwise, if it is false then gitweb would process config file only once;
928 # if it is true then gitweb config would be run for each request.
929 our $per_request_config = 1;
931 # If true and fileno STDIN is 0 and getsockname succeeds and getpeername fails
932 # with ENOTCONN, then FCGI mode will be activated automatically in just the
933 # same way as though the --fcgi option had been given instead.
934 our $auto_fcgi = 0;
936 # read and parse gitweb config file given by its parameter.
937 # returns true on success, false on recoverable error, allowing
938 # to chain this subroutine, using first file that exists.
939 # dies on errors during parsing config file, as it is unrecoverable.
940 sub read_config_file {
941 my $filename = shift;
942 return unless defined $filename;
943 # die if there are errors parsing config file
944 if (-e $filename) {
945 do $filename;
946 die $@ if $@;
947 return 1;
949 return;
952 our ($GITWEB_CONFIG, $GITWEB_CONFIG_SYSTEM, $GITWEB_CONFIG_COMMON);
953 sub evaluate_gitweb_config {
954 our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "++GITWEB_CONFIG++";
955 our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "++GITWEB_CONFIG_SYSTEM++";
956 our $GITWEB_CONFIG_COMMON = $ENV{'GITWEB_CONFIG_COMMON'} || "++GITWEB_CONFIG_COMMON++";
958 # Protect against duplications of file names, to not read config twice.
959 # Only one of $GITWEB_CONFIG and $GITWEB_CONFIG_SYSTEM is used, so
960 # there possibility of duplication of filename there doesn't matter.
961 $GITWEB_CONFIG = "" if ($GITWEB_CONFIG eq $GITWEB_CONFIG_COMMON);
962 $GITWEB_CONFIG_SYSTEM = "" if ($GITWEB_CONFIG_SYSTEM eq $GITWEB_CONFIG_COMMON);
964 # Common system-wide settings for convenience.
965 # Those settings can be ovverriden by GITWEB_CONFIG or GITWEB_CONFIG_SYSTEM.
966 read_config_file($GITWEB_CONFIG_COMMON);
968 # Use first config file that exists. This means use the per-instance
969 # GITWEB_CONFIG if exists, otherwise use GITWEB_SYSTEM_CONFIG.
970 read_config_file($GITWEB_CONFIG) and return;
971 read_config_file($GITWEB_CONFIG_SYSTEM);
974 our $encode_object;
976 sub evaluate_encoding {
977 my $requested = $fallback_encoding || 'ISO-8859-1';
978 my $obj = Encode::find_encoding($requested) or
979 die_error(400, "Requested fallback encoding not found");
980 if ($obj->name eq 'iso-8859-1') {
981 # Use Windows-1252 instead as required by the HTML 5 standard
982 my $altobj = Encode::find_encoding('Windows-1252');
983 $obj = $altobj if $altobj;
985 $encode_object = $obj;
988 sub evaluate_email_obfuscate {
989 # email obfuscation
990 our $email;
991 if (!$email && eval { require HTML::Email::Obfuscate; 1 }) {
992 $email = HTML::Email::Obfuscate->new(lite => 1);
996 # Get loadavg of system, to compare against $maxload.
997 # Currently it requires '/proc/loadavg' present to get loadavg;
998 # if it is not present it returns 0, which means no load checking.
999 sub get_loadavg {
1000 if( -e '/proc/loadavg' ){
1001 open my $fd, '<', '/proc/loadavg'
1002 or return 0;
1003 my @load = split(/\s+/, scalar <$fd>);
1004 close $fd;
1006 # The first three columns measure CPU and IO utilization of the last one,
1007 # five, and 10 minute periods. The fourth column shows the number of
1008 # currently running processes and the total number of processes in the m/n
1009 # format. The last column displays the last process ID used.
1010 return $load[0] || 0;
1012 # additional checks for load average should go here for things that don't export
1013 # /proc/loadavg
1015 return 0;
1018 # version of the core git binary
1019 our $git_version;
1020 sub evaluate_git_version {
1021 our $git_version = $version;
1024 sub check_loadavg {
1025 if (defined $maxload && get_loadavg() > $maxload) {
1026 die_error(503, "The load average on the server is too high");
1030 # ======================================================================
1031 # input validation and dispatch
1033 # input parameters can be collected from a variety of sources (presently, CGI
1034 # and PATH_INFO), so we define an %input_params hash that collects them all
1035 # together during validation: this allows subsequent uses (e.g. href()) to be
1036 # agnostic of the parameter origin
1038 our %input_params = ();
1040 # input parameters are stored with the long parameter name as key. This will
1041 # also be used in the href subroutine to convert parameters to their CGI
1042 # equivalent, and since the href() usage is the most frequent one, we store
1043 # the name -> CGI key mapping here, instead of the reverse.
1045 # XXX: Warning: If you touch this, check the search form for updating,
1046 # too.
1048 our @cgi_param_mapping = (
1049 project => "p",
1050 action => "a",
1051 file_name => "f",
1052 file_parent => "fp",
1053 hash => "h",
1054 hash_parent => "hp",
1055 hash_base => "hb",
1056 hash_parent_base => "hpb",
1057 page => "pg",
1058 order => "o",
1059 searchtext => "s",
1060 searchtype => "st",
1061 snapshot_format => "sf",
1062 ctag_filter => 't',
1063 extra_options => "opt",
1064 search_use_regexp => "sr",
1065 ctag => "by_tag",
1066 diff_style => "ds",
1067 project_filter => "pf",
1068 # this must be last entry (for manipulation from JavaScript)
1069 javascript => "js"
1071 our %cgi_param_mapping = @cgi_param_mapping;
1073 # we will also need to know the possible actions, for validation
1074 our %actions = (
1075 "blame" => \&git_blame,
1076 "blame_incremental" => \&git_blame_incremental,
1077 "blame_data" => \&git_blame_data,
1078 "blobdiff" => \&git_blobdiff,
1079 "blobdiff_plain" => \&git_blobdiff_plain,
1080 "blob" => \&git_blob,
1081 "blob_plain" => \&git_blob_plain,
1082 "commitdiff" => \&git_commitdiff,
1083 "commitdiff_plain" => \&git_commitdiff_plain,
1084 "commit" => \&git_commit,
1085 "forks" => \&git_forks,
1086 "heads" => \&git_heads,
1087 "history" => \&git_history,
1088 "log" => \&git_log,
1089 "patch" => \&git_patch,
1090 "patches" => \&git_patches,
1091 "refs" => \&git_refs,
1092 "remotes" => \&git_remotes,
1093 "rss" => \&git_rss,
1094 "atom" => \&git_atom,
1095 "search" => \&git_search,
1096 "search_help" => \&git_search_help,
1097 "shortlog" => \&git_shortlog,
1098 "summary" => \&git_summary,
1099 "tag" => \&git_tag,
1100 "tags" => \&git_tags,
1101 "tree" => \&git_tree,
1102 "snapshot" => \&git_snapshot,
1103 "object" => \&git_object,
1104 # those below don't need $project
1105 "opml" => \&git_opml,
1106 "frontpage" => \&git_frontpage,
1107 "project_list" => \&git_project_list,
1108 "project_index" => \&git_project_index,
1111 # the only actions we will allow to be cached
1112 my %supported_cache_actions;
1113 BEGIN {%supported_cache_actions = map {( $_ => 1 )} qw(summary)}
1115 # finally, we have the hash of allowed extra_options for the commands that
1116 # allow them
1117 our %allowed_options = (
1118 "--no-merges" => [ qw(rss atom log shortlog history) ],
1121 # fill %input_params with the CGI parameters. All values except for 'opt'
1122 # should be single values, but opt can be an array. We should probably
1123 # build an array of parameters that can be multi-valued, but since for the time
1124 # being it's only this one, we just single it out
1125 sub evaluate_query_params {
1126 our $cgi;
1128 while (my ($name, $symbol) = each %cgi_param_mapping) {
1129 if ($symbol eq 'opt') {
1130 $input_params{$name} = [ map { decode_utf8($_) } $cgi->multi_param($symbol) ];
1131 } else {
1132 $input_params{$name} = decode_utf8($cgi->param($symbol));
1136 # Backwards compatibility - by_tag= <=> t=
1137 if ($input_params{'ctag'}) {
1138 $input_params{'ctag_filter'} = $input_params{'ctag'};
1142 # now read PATH_INFO and update the parameter list for missing parameters
1143 sub evaluate_path_info {
1144 return if defined $input_params{'project'};
1145 return if !$path_info;
1146 $path_info =~ s,^/+,,;
1147 return if !$path_info;
1149 # find which part of PATH_INFO is project
1150 my $project = $path_info;
1151 $project =~ s,/+$,,;
1152 while ($project && !check_head_link("$projectroot/$project")) {
1153 $project =~ s,/*[^/]*$,,;
1155 return unless $project;
1156 $input_params{'project'} = $project;
1158 # do not change any parameters if an action is given using the query string
1159 return if $input_params{'action'};
1160 $path_info =~ s,^\Q$project\E/*,,;
1162 # next, check if we have an action
1163 my $action = $path_info;
1164 $action =~ s,/.*$,,;
1165 if (exists $actions{$action}) {
1166 $path_info =~ s,^$action/*,,;
1167 $input_params{'action'} = $action;
1170 # list of actions that want hash_base instead of hash, but can have no
1171 # pathname (f) parameter
1172 my @wants_base = (
1173 'tree',
1174 'history',
1177 # we want to catch, among others
1178 # [$hash_parent_base[:$file_parent]..]$hash_parent[:$file_name]
1179 my ($parentrefname, $parentpathname, $refname, $pathname) =
1180 ($path_info =~ /^(?:(.+?)(?::(.+))?\.\.)?([^:]+?)?(?::(.+))?$/);
1182 # first, analyze the 'current' part
1183 if (defined $pathname) {
1184 # we got "branch:filename" or "branch:dir/"
1185 # we could use git_get_type(branch:pathname), but:
1186 # - it needs $git_dir
1187 # - it does a git() call
1188 # - the convention of terminating directories with a slash
1189 # makes it superfluous
1190 # - embedding the action in the PATH_INFO would make it even
1191 # more superfluous
1192 $pathname =~ s,^/+,,;
1193 if (!$pathname || substr($pathname, -1) eq "/") {
1194 $input_params{'action'} ||= "tree";
1195 $pathname =~ s,/$,,;
1196 } else {
1197 # the default action depends on whether we had parent info
1198 # or not
1199 if ($parentrefname) {
1200 $input_params{'action'} ||= "blobdiff_plain";
1201 } else {
1202 $input_params{'action'} ||= "blob_plain";
1205 $input_params{'hash_base'} ||= $refname;
1206 $input_params{'file_name'} ||= $pathname;
1207 } elsif (defined $refname) {
1208 # we got "branch". In this case we have to choose if we have to
1209 # set hash or hash_base.
1211 # Most of the actions without a pathname only want hash to be
1212 # set, except for the ones specified in @wants_base that want
1213 # hash_base instead. It should also be noted that hand-crafted
1214 # links having 'history' as an action and no pathname or hash
1215 # set will fail, but that happens regardless of PATH_INFO.
1216 if (defined $parentrefname) {
1217 # if there is parent let the default be 'shortlog' action
1218 # (for http://git.example.com/repo.git/A..B links); if there
1219 # is no parent, dispatch will detect type of object and set
1220 # action appropriately if required (if action is not set)
1221 $input_params{'action'} ||= "shortlog";
1223 if ($input_params{'action'} &&
1224 grep { $_ eq $input_params{'action'} } @wants_base) {
1225 $input_params{'hash_base'} ||= $refname;
1226 } else {
1227 $input_params{'hash'} ||= $refname;
1231 # next, handle the 'parent' part, if present
1232 if (defined $parentrefname) {
1233 # a missing pathspec defaults to the 'current' filename, allowing e.g.
1234 # someproject/blobdiff/oldrev..newrev:/filename
1235 if ($parentpathname) {
1236 $parentpathname =~ s,^/+,,;
1237 $parentpathname =~ s,/$,,;
1238 $input_params{'file_parent'} ||= $parentpathname;
1239 } else {
1240 $input_params{'file_parent'} ||= $input_params{'file_name'};
1242 # we assume that hash_parent_base is wanted if a path was specified,
1243 # or if the action wants hash_base instead of hash
1244 if (defined $input_params{'file_parent'} ||
1245 grep { $_ eq $input_params{'action'} } @wants_base) {
1246 $input_params{'hash_parent_base'} ||= $parentrefname;
1247 } else {
1248 $input_params{'hash_parent'} ||= $parentrefname;
1252 # for the snapshot action, we allow URLs in the form
1253 # $project/snapshot/$hash.ext
1254 # where .ext determines the snapshot and gets removed from the
1255 # passed $refname to provide the $hash.
1257 # To be able to tell that $refname includes the format extension, we
1258 # require the following two conditions to be satisfied:
1259 # - the hash input parameter MUST have been set from the $refname part
1260 # of the URL (i.e. they must be equal)
1261 # - the snapshot format MUST NOT have been defined already (e.g. from
1262 # CGI parameter sf)
1263 # It's also useless to try any matching unless $refname has a dot,
1264 # so we check for that too
1265 if (defined $input_params{'action'} &&
1266 $input_params{'action'} eq 'snapshot' &&
1267 defined $refname && index($refname, '.') != -1 &&
1268 $refname eq $input_params{'hash'} &&
1269 !defined $input_params{'snapshot_format'}) {
1270 # We loop over the known snapshot formats, checking for
1271 # extensions. Allowed extensions are both the defined suffix
1272 # (which includes the initial dot already) and the snapshot
1273 # format key itself, with a prepended dot
1274 while (my ($fmt, $opt) = each %known_snapshot_formats) {
1275 my $hash = $refname;
1276 unless ($hash =~ s/(\Q$opt->{'suffix'}\E|\Q.$fmt\E)$//) {
1277 next;
1279 my $sfx = $1;
1280 # a valid suffix was found, so set the snapshot format
1281 # and reset the hash parameter
1282 $input_params{'snapshot_format'} = $fmt;
1283 $input_params{'hash'} = $hash;
1284 # we also set the format suffix to the one requested
1285 # in the URL: this way a request for e.g. .tgz returns
1286 # a .tgz instead of a .tar.gz
1287 $known_snapshot_formats{$fmt}{'suffix'} = $sfx;
1288 last;
1293 our ($action, $project, $file_name, $file_parent, $hash, $hash_parent, $hash_base,
1294 $hash_parent_base, @extra_options, $page, $searchtype, $search_use_regexp,
1295 $searchtext, $search_regexp, $project_filter);
1296 sub evaluate_and_validate_params {
1297 our $action = $input_params{'action'};
1298 if (defined $action) {
1299 if (!is_valid_action($action)) {
1300 die_error(400, "Invalid action parameter");
1304 # parameters which are pathnames
1305 our $project = $input_params{'project'};
1306 if (defined $project) {
1307 if (!is_valid_project($project)) {
1308 undef $project;
1309 die_error(404, "No such project");
1313 our $project_filter = $input_params{'project_filter'};
1314 if (defined $project_filter) {
1315 if (!is_valid_pathname($project_filter)) {
1316 die_error(404, "Invalid project_filter parameter");
1320 our $file_name = $input_params{'file_name'};
1321 if (defined $file_name) {
1322 if (!is_valid_pathname($file_name)) {
1323 die_error(400, "Invalid file parameter");
1327 our $file_parent = $input_params{'file_parent'};
1328 if (defined $file_parent) {
1329 if (!is_valid_pathname($file_parent)) {
1330 die_error(400, "Invalid file parent parameter");
1334 # parameters which are refnames
1335 our $hash = $input_params{'hash'};
1336 if (defined $hash) {
1337 if (!is_valid_refname($hash)) {
1338 die_error(400, "Invalid hash parameter");
1342 our $hash_parent = $input_params{'hash_parent'};
1343 if (defined $hash_parent) {
1344 if (!is_valid_refname($hash_parent)) {
1345 die_error(400, "Invalid hash parent parameter");
1349 our $hash_base = $input_params{'hash_base'};
1350 if (defined $hash_base) {
1351 if (!is_valid_refname($hash_base)) {
1352 die_error(400, "Invalid hash base parameter");
1356 our @extra_options = @{$input_params{'extra_options'}};
1357 # @extra_options is always defined, since it can only be (currently) set from
1358 # CGI, and $cgi->param() returns the empty array in array context if the param
1359 # is not set
1360 foreach my $opt (@extra_options) {
1361 if (not exists $allowed_options{$opt}) {
1362 die_error(400, "Invalid option parameter");
1364 if (not grep(/^$action$/, @{$allowed_options{$opt}})) {
1365 die_error(400, "Invalid option parameter for this action");
1369 our $hash_parent_base = $input_params{'hash_parent_base'};
1370 if (defined $hash_parent_base) {
1371 if (!is_valid_refname($hash_parent_base)) {
1372 die_error(400, "Invalid hash parent base parameter");
1376 # other parameters
1377 our $page = $input_params{'page'};
1378 if (defined $page) {
1379 if ($page =~ m/[^0-9]/) {
1380 die_error(400, "Invalid page parameter");
1384 our $searchtype = $input_params{'searchtype'};
1385 if (defined $searchtype) {
1386 if ($searchtype =~ m/[^a-z]/) {
1387 die_error(400, "Invalid searchtype parameter");
1391 our $search_use_regexp = $input_params{'search_use_regexp'};
1393 our $searchtext = $input_params{'searchtext'};
1394 our $search_regexp = undef;
1395 if (defined $searchtext) {
1396 if (length($searchtext) < 2) {
1397 die_error(403, "At least two characters are required for search parameter");
1399 if ($search_use_regexp) {
1400 $search_regexp = $searchtext;
1401 if (!eval { qr/$search_regexp/; 1; }) {
1402 (my $error = $@) =~ s/ at \S+ line \d+.*\n?//;
1403 die_error(400, "Invalid search regexp '$search_regexp'",
1404 esc_html($error));
1406 } else {
1407 $search_regexp = quotemeta $searchtext;
1412 # path to the current git repository
1413 our $git_dir;
1414 sub evaluate_git_dir {
1415 our $git_dir = $project ? "$projectroot/$project" : undef;
1418 our (@snapshot_fmts, $git_avatar, @extra_branch_refs);
1419 sub configure_gitweb_features {
1420 # list of supported snapshot formats
1421 our @snapshot_fmts = gitweb_get_feature('snapshot');
1422 @snapshot_fmts = filter_snapshot_fmts(@snapshot_fmts);
1424 # check that the avatar feature is set to a known provider name,
1425 # and for each provider check if the dependencies are satisfied.
1426 # if the provider name is invalid or the dependencies are not met,
1427 # reset $git_avatar to the empty string.
1428 our ($git_avatar) = gitweb_get_feature('avatar');
1429 if ($git_avatar eq 'gravatar') {
1430 $git_avatar = '' unless (eval { require Digest::MD5; 1; });
1431 } elsif ($git_avatar eq 'picon') {
1432 # no dependencies
1433 } else {
1434 $git_avatar = '';
1437 our @extra_branch_refs = gitweb_get_feature('extra-branch-refs');
1438 @extra_branch_refs = filter_and_validate_refs (@extra_branch_refs);
1441 sub get_branch_refs {
1442 return ('heads', @extra_branch_refs);
1445 # custom error handler: 'die <message>' is Internal Server Error
1446 sub handle_errors_html {
1447 my $msg = shift; # it is already HTML escaped
1449 # to avoid infinite loop where error occurs in die_error,
1450 # change handler to default handler, disabling handle_errors_html
1451 set_message("Error occurred when inside die_error:\n$msg");
1453 # you cannot jump out of die_error when called as error handler;
1454 # the subroutine set via CGI::Carp::set_message is called _after_
1455 # HTTP headers are already written, so it cannot write them itself
1456 die_error(undef, undef, $msg, -error_handler => 1, -no_http_header => 1);
1458 set_message(\&handle_errors_html);
1460 our $shown_stale_message = 0;
1461 our $cache_dump = undef;
1462 our $cache_dump_mtime = undef;
1464 # dispatch
1465 my $cache_mode_active;
1466 sub dispatch {
1467 $shown_stale_message = 0;
1468 if (!defined $action) {
1469 if (defined $hash) {
1470 $action = git_get_type($hash);
1471 $action or die_error(404, "Object does not exist");
1472 } elsif (defined $hash_base && defined $file_name) {
1473 $action = git_get_type("$hash_base:$file_name");
1474 $action or die_error(404, "File or directory does not exist");
1475 } elsif (defined $project) {
1476 $action = 'summary';
1477 } else {
1478 $action = 'frontpage';
1481 if (!defined($actions{$action})) {
1482 die_error(400, "Unknown action");
1484 if ($action !~ m/^(?:opml|frontpage|project_list|project_index)$/ &&
1485 !$project) {
1486 die_error(400, "Project needed");
1489 my $cached_page = $supported_cache_actions{$action}
1490 ? cached_action_page($action)
1491 : undef;
1492 goto DUMPCACHE if $cached_page;
1493 local *SAVEOUT = *STDOUT;
1494 $cache_mode_active = $supported_cache_actions{$action}
1495 ? cached_action_start($action)
1496 : undef;
1498 configure_gitweb_features();
1499 $actions{$action}->();
1501 return unless $cache_mode_active;
1503 $cached_page = cached_action_finish($action);
1504 *STDOUT = *SAVEOUT;
1506 DUMPCACHE:
1508 $cache_mode_active = 0;
1509 # Avoid any extra unwanted encoding steps as $cached_page is raw bytes
1510 binmode STDOUT, ':raw';
1511 our $fcgi_raw_mode = 1;
1512 print expand_gitweb_pi($cached_page, time);
1513 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
1514 $fcgi_raw_mode = 0;
1517 sub reset_timer {
1518 our $t0 = [ gettimeofday() ]
1519 if defined $t0;
1520 our $number_of_git_cmds = 0;
1523 our $first_request = 1;
1524 our $evaluate_uri_force = undef;
1525 sub run_request {
1526 reset_timer();
1528 # do not reuse stale config or project list from prior FCGI request
1529 our $config_file = '';
1530 our $gitweb_project_owner = undef;
1532 # Only allow GET and HEAD methods
1533 if (!$ENV{'REQUEST_METHOD'} || ($ENV{'REQUEST_METHOD'} ne 'GET' && $ENV{'REQUEST_METHOD'} ne 'HEAD')) {
1534 print <<EOT;
1535 Status: 405 Method Not Allowed
1536 Content-Type: text/plain
1537 Allow: GET,HEAD
1539 405 Method Not Allowed
1541 return;
1544 evaluate_uri();
1545 &$evaluate_uri_force() if $evaluate_uri_force;
1546 if ($per_request_config) {
1547 if (ref($per_request_config) eq 'CODE') {
1548 $per_request_config->();
1549 } elsif (!$first_request) {
1550 evaluate_gitweb_config();
1551 evaluate_email_obfuscate();
1554 check_loadavg();
1556 # $projectroot and $projects_list might be set in gitweb config file
1557 $projects_list ||= $projectroot;
1559 evaluate_query_params();
1560 evaluate_path_info();
1561 evaluate_and_validate_params();
1562 evaluate_git_dir();
1564 dispatch();
1567 our $is_last_request = sub { 1 };
1568 our ($pre_dispatch_hook, $post_dispatch_hook, $pre_listen_hook);
1569 our $CGI = 'CGI';
1570 our $cgi;
1571 our $fcgi_mode = 0;
1572 our $fcgi_nproc_active = 0;
1573 our $fcgi_raw_mode = 0;
1574 sub is_fcgi {
1575 use Errno;
1576 my $stdinfno = fileno STDIN;
1577 return 0 unless defined $stdinfno && $stdinfno == 0;
1578 return 0 unless getsockname STDIN;
1579 return 0 if getpeername STDIN;
1580 return $!{ENOTCONN}?1:0;
1582 sub configure_as_fcgi {
1583 return if $fcgi_mode;
1585 require FCGI;
1586 require CGI::Fast;
1588 # We have gone to great effort to make sure that all incoming data has
1589 # been converted from whatever format it was in into UTF-8. We have
1590 # even taken care to make sure the output handle is in ':utf8' mode.
1591 # Now along comes FCGI and blows it with:
1593 # Use of wide characters in FCGI::Stream::PRINT is deprecated
1594 # and will stop wprking[sic] in a future version of FCGI
1596 # To fix this we replace FCGI::Stream::PRINT with our own routine that
1597 # first encodes everything and then calls the original routine, but
1598 # not if $fcgi_raw_mode is true (then we just call the original routine).
1600 # Note that we could do this by using utf8::is_utf8 to check instead
1601 # of having a $fcgi_raw_mode global, but that would be slower to run
1602 # the test on each element and much slower than skipping the conversion
1603 # entirely when we know we're outputting raw bytes.
1604 my $orig = \&FCGI::Stream::PRINT;
1605 undef *FCGI::Stream::PRINT;
1606 *FCGI::Stream::PRINT = sub {
1607 @_ = (shift, map {my $x=$_; utf8::encode($x); $x} @_)
1608 unless $fcgi_raw_mode;
1609 goto $orig;
1612 our $CGI = 'CGI::Fast';
1614 $fcgi_mode = 1;
1615 $first_request = 0;
1616 my $request_number = 0;
1617 # let each child service 100 requests
1618 our $is_last_request = sub { ++$request_number > 100 };
1620 sub evaluate_argv {
1621 my $script_name = $ENV{'SCRIPT_NAME'} || $ENV{'SCRIPT_FILENAME'} || __FILE__;
1622 configure_as_fcgi()
1623 if $script_name =~ /\.fcgi$/ || ($auto_fcgi && is_fcgi());
1625 my $nproc_sub = sub {
1626 my ($arg, $val) = @_;
1627 return unless eval { require FCGI::ProcManager; 1; };
1628 $fcgi_nproc_active = 1;
1629 my $proc_manager = FCGI::ProcManager->new({
1630 n_processes => $val,
1632 our $pre_listen_hook = sub { $proc_manager->pm_manage() };
1633 our $pre_dispatch_hook = sub { $proc_manager->pm_pre_dispatch() };
1634 our $post_dispatch_hook = sub { $proc_manager->pm_post_dispatch() };
1636 if (@ARGV) {
1637 require Getopt::Long;
1638 Getopt::Long::GetOptions(
1639 'fastcgi|fcgi|f' => \&configure_as_fcgi,
1640 'nproc|n=i' => $nproc_sub,
1643 if (!$fcgi_nproc_active && defined $ENV{'GITWEB_FCGI_NPROC'} && $ENV{'GITWEB_FCGI_NPROC'} =~ /^\d+$/) {
1644 &$nproc_sub('nproc', $ENV{'GITWEB_FCGI_NPROC'});
1648 sub run {
1649 evaluate_gitweb_config();
1650 evaluate_encoding();
1651 evaluate_email_obfuscate();
1652 evaluate_git_version();
1653 my ($mu, $hl, $subroutine) = ($my_uri, $home_link, '');
1654 $subroutine .= '$my_uri = $mu;' if defined $my_uri && $my_uri ne '';
1655 $subroutine .= '$home_link = $hl;' if defined $home_link && $home_link ne '';
1656 $evaluate_uri_force = eval "sub {$subroutine}" if $subroutine;
1657 $first_request = 1;
1658 evaluate_argv();
1660 $pre_listen_hook->()
1661 if $pre_listen_hook;
1663 REQUEST:
1664 while ($cgi = $CGI->new()) {
1665 $pre_dispatch_hook->()
1666 if $pre_dispatch_hook;
1668 run_request();
1670 $post_dispatch_hook->()
1671 if $post_dispatch_hook;
1672 $first_request = 0;
1674 last REQUEST if ($is_last_request->());
1677 DONE_GITWEB:
1681 run();
1683 if (defined caller) {
1684 # wrapped in a subroutine processing requests,
1685 # e.g. mod_perl with ModPerl::Registry, or PSGI with Plack::App::WrapCGI
1686 return;
1687 } else {
1688 # pure CGI script, serving single request
1689 exit;
1692 ## ======================================================================
1693 ## action links
1695 # possible values of extra options
1696 # -full => 0|1 - use absolute/full URL ($my_uri/$my_url as base)
1697 # -replay => 1 - start from a current view (replay with modifications)
1698 # -path_info => 0|1 - don't use/use path_info URL (if possible)
1699 # -anchor => ANCHOR - add #ANCHOR to end of URL, implies -replay if used alone
1700 sub href {
1701 my %params = @_;
1702 # default is to use -absolute url() i.e. $my_uri
1703 my $href = $params{-full} ? $my_url : $my_uri;
1705 # implicit -replay, must be first of implicit params
1706 $params{-replay} = 1 if (keys %params == 1 && $params{-anchor});
1708 $params{'project'} = $project unless exists $params{'project'};
1710 if ($params{-replay}) {
1711 while (my ($name, $symbol) = each %cgi_param_mapping) {
1712 if (!exists $params{$name}) {
1713 $params{$name} = $input_params{$name};
1718 my $use_pathinfo = gitweb_check_feature('pathinfo');
1719 if (defined $params{'project'} &&
1720 (exists $params{-path_info} ? $params{-path_info} : $use_pathinfo)) {
1721 # try to put as many parameters as possible in PATH_INFO:
1722 # - project name
1723 # - action
1724 # - hash_parent or hash_parent_base:/file_parent
1725 # - hash or hash_base:/filename
1726 # - the snapshot_format as an appropriate suffix
1728 # When the script is the root DirectoryIndex for the domain,
1729 # $href here would be something like http://gitweb.example.com/
1730 # Thus, we strip any trailing / from $href, to spare us double
1731 # slashes in the final URL
1732 $href =~ s,/$,,;
1734 # Then add the project name, if present
1735 $href .= "/".esc_path_info($params{'project'});
1736 delete $params{'project'};
1738 # since we destructively absorb parameters, we keep this
1739 # boolean that remembers if we're handling a snapshot
1740 my $is_snapshot = $params{'action'} eq 'snapshot';
1742 # Summary just uses the project path URL, any other action is
1743 # added to the URL
1744 if (defined $params{'action'}) {
1745 $href .= "/".esc_path_info($params{'action'})
1746 unless $params{'action'} eq 'summary';
1747 delete $params{'action'};
1750 # Next, we put hash_parent_base:/file_parent..hash_base:/file_name,
1751 # stripping nonexistent or useless pieces
1752 $href .= "/" if ($params{'hash_base'} || $params{'hash_parent_base'}
1753 || $params{'hash_parent'} || $params{'hash'});
1754 if (defined $params{'hash_base'}) {
1755 if (defined $params{'hash_parent_base'}) {
1756 $href .= esc_path_info($params{'hash_parent_base'});
1757 # skip the file_parent if it's the same as the file_name
1758 if (defined $params{'file_parent'}) {
1759 if (defined $params{'file_name'} && $params{'file_parent'} eq $params{'file_name'}) {
1760 delete $params{'file_parent'};
1761 } elsif ($params{'file_parent'} !~ /\.\./) {
1762 $href .= ":/".esc_path_info($params{'file_parent'});
1763 delete $params{'file_parent'};
1766 $href .= "..";
1767 delete $params{'hash_parent'};
1768 delete $params{'hash_parent_base'};
1769 } elsif (defined $params{'hash_parent'}) {
1770 $href .= esc_path_info($params{'hash_parent'}). "..";
1771 delete $params{'hash_parent'};
1774 $href .= esc_path_info($params{'hash_base'});
1775 if (defined $params{'file_name'} && $params{'file_name'} !~ /\.\./) {
1776 $href .= ":/".esc_path_info($params{'file_name'});
1777 delete $params{'file_name'};
1779 delete $params{'hash'};
1780 delete $params{'hash_base'};
1781 } elsif (defined $params{'hash'}) {
1782 $href .= esc_path_info($params{'hash'});
1783 delete $params{'hash'};
1786 # If the action was a snapshot, we can absorb the
1787 # snapshot_format parameter too
1788 if ($is_snapshot) {
1789 my $fmt = $params{'snapshot_format'};
1790 # snapshot_format should always be defined when href()
1791 # is called, but just in case some code forgets, we
1792 # fall back to the default
1793 $fmt ||= $snapshot_fmts[0];
1794 $href .= $known_snapshot_formats{$fmt}{'suffix'};
1795 delete $params{'snapshot_format'};
1799 # now encode the parameters explicitly
1800 my @result = ();
1801 for (my $i = 0; $i < @cgi_param_mapping; $i += 2) {
1802 my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]);
1803 if (defined $params{$name}) {
1804 if (ref($params{$name}) eq "ARRAY") {
1805 foreach my $par (@{$params{$name}}) {
1806 push @result, $symbol . "=" . esc_param($par);
1808 } else {
1809 push @result, $symbol . "=" . esc_param($params{$name});
1813 $href .= "?" . join(';', @result) if scalar @result;
1815 # final transformation: trailing spaces must be escaped (URI-encoded)
1816 $href =~ s/(\s+)$/CGI::escape($1)/e;
1818 if ($params{-anchor}) {
1819 $href .= "#".esc_param($params{-anchor});
1822 return $href;
1826 ## ======================================================================
1827 ## validation, quoting/unquoting and escaping
1829 sub is_valid_action {
1830 my $input = shift;
1831 return undef unless exists $actions{$input};
1832 return 1;
1835 sub is_valid_project {
1836 my $input = shift;
1838 return unless defined $input;
1839 if (!is_valid_pathname($input) ||
1840 !(-d "$projectroot/$input") ||
1841 !check_export_ok("$projectroot/$input") ||
1842 ($strict_export && !project_in_list($input))) {
1843 return undef;
1844 } else {
1845 return 1;
1849 sub is_valid_pathname {
1850 my $input = shift;
1852 return undef unless defined $input;
1853 # no '.' or '..' as elements of path, i.e. no '.' or '..'
1854 # at the beginning, at the end, and between slashes.
1855 # also this catches doubled slashes
1856 if ($input =~ m!(^|/)(|\.|\.\.)(/|$)!) {
1857 return undef;
1859 # no null characters
1860 if ($input =~ m!\0!) {
1861 return undef;
1863 return 1;
1866 sub is_valid_ref_format {
1867 my $input = shift;
1869 return undef unless defined $input;
1870 # restrictions on ref name according to git-check-ref-format
1871 if ($input =~ m!(/\.|\.\.|[\000-\040\177 ~^:?*\[]|/$)!) {
1872 return undef;
1874 return 1;
1877 sub is_valid_refname {
1878 my $input = shift;
1880 return undef unless defined $input;
1881 # textual hashes are O.K.
1882 if ($input =~ m/^[0-9a-fA-F]{40}$/) {
1883 return 1;
1885 # it must be correct pathname
1886 is_valid_pathname($input) or return undef;
1887 # check git-check-ref-format restrictions
1888 is_valid_ref_format($input) or return undef;
1889 return 1;
1892 # decode sequences of octets in utf8 into Perl's internal form,
1893 # which is utf-8 with utf8 flag set if needed. gitweb writes out
1894 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
1895 sub to_utf8 {
1896 my $str = shift;
1897 return undef unless defined $str;
1899 if (utf8::is_utf8($str) || utf8::decode($str)) {
1900 return $str;
1901 } else {
1902 return $encode_object->decode($str, Encode::FB_DEFAULT);
1906 # quote unsafe chars, but keep the slash, even when it's not
1907 # correct, but quoted slashes look too horrible in bookmarks
1908 sub esc_param {
1909 my $str = shift;
1910 return undef unless defined $str;
1911 $str =~ s/([^A-Za-z0-9\-_.~()\/:@ ]+)/CGI::escape($1)/eg;
1912 $str =~ s/ /\+/g;
1913 return $str;
1916 # the quoting rules for path_info fragment are slightly different
1917 sub esc_path_info {
1918 my $str = shift;
1919 return undef unless defined $str;
1921 # path_info doesn't treat '+' as space (specially), but '?' must be escaped
1922 $str =~ s/([^A-Za-z0-9\-_.~();\/;:@&= +]+)/CGI::escape($1)/eg;
1924 return $str;
1927 # quote unsafe chars in whole URL, so some characters cannot be quoted
1928 sub esc_url {
1929 my $str = shift;
1930 return undef unless defined $str;
1931 $str =~ s/([^A-Za-z0-9\-_.~();\/;?:@&= ]+)/CGI::escape($1)/eg;
1932 $str =~ s/ /\+/g;
1933 return $str;
1936 # quote unsafe characters in HTML attributes
1937 sub esc_attr {
1939 # for XHTML conformance escaping '"' to '&quot;' is not enough
1940 return esc_html(@_);
1943 # replace invalid utf8 character with SUBSTITUTION sequence
1944 sub esc_html {
1945 my $str = shift;
1946 my %opts = @_;
1948 return undef unless defined $str;
1950 $str = to_utf8($str);
1951 $str = $cgi->escapeHTML($str);
1952 if ($opts{'-nbsp'}) {
1953 $str =~ s/ /&#160;/g;
1955 use bytes;
1956 $str =~ s|([[:cntrl:]])|(($1 ne "\t") ? quot_cec($1) : $1)|eg;
1957 return $str;
1960 # quote control characters and escape filename to HTML
1961 sub esc_path {
1962 my $str = shift;
1963 my %opts = @_;
1965 return undef unless defined $str;
1967 $str = to_utf8($str);
1968 $str = $cgi->escapeHTML($str);
1969 if ($opts{'-nbsp'}) {
1970 $str =~ s/ /&#160;/g;
1972 use bytes;
1973 $str =~ s|([[:cntrl:]])|quot_cec($1)|eg;
1974 return $str;
1977 # Sanitize for use in XHTML + application/xml+xhtm (valid XML 1.0)
1978 sub sanitize {
1979 my $str = shift;
1981 return undef unless defined $str;
1983 $str = to_utf8($str);
1984 use bytes;
1985 $str =~ s|([[:cntrl:]])|(index("\t\n\r", $1) != -1 ? $1 : quot_cec($1))|eg;
1986 return $str;
1989 # Make control characters "printable", using character escape codes (CEC)
1990 sub quot_cec {
1991 my $cntrl = shift;
1992 my %opts = @_;
1993 my %es = ( # character escape codes, aka escape sequences
1994 "\t" => '\t', # tab (HT)
1995 "\n" => '\n', # line feed (LF)
1996 "\r" => '\r', # carrige return (CR)
1997 "\f" => '\f', # form feed (FF)
1998 "\b" => '\b', # backspace (BS)
1999 "\a" => '\a', # alarm (bell) (BEL)
2000 "\e" => '\e', # escape (ESC)
2001 "\013" => '\v', # vertical tab (VT)
2002 "\000" => '\0', # nul character (NUL)
2004 my $chr = ( (exists $es{$cntrl})
2005 ? $es{$cntrl}
2006 : sprintf('\x%02x', ord($cntrl)) );
2007 if ($opts{-nohtml}) {
2008 return $chr;
2009 } else {
2010 return "<span class=\"cntrl\">$chr</span>";
2014 # Alternatively use unicode control pictures codepoints,
2015 # Unicode "printable representation" (PR)
2016 sub quot_upr {
2017 my $cntrl = shift;
2018 my %opts = @_;
2020 my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
2021 if ($opts{-nohtml}) {
2022 return $chr;
2023 } else {
2024 return "<span class=\"cntrl\">$chr</span>";
2028 # git may return quoted and escaped filenames
2029 sub unquote {
2030 my $str = shift;
2032 sub unq {
2033 my $seq = shift;
2034 my %es = ( # character escape codes, aka escape sequences
2035 't' => "\t", # tab (HT, TAB)
2036 'n' => "\n", # newline (NL)
2037 'r' => "\r", # return (CR)
2038 'f' => "\f", # form feed (FF)
2039 'b' => "\b", # backspace (BS)
2040 'a' => "\a", # alarm (bell) (BEL)
2041 'e' => "\e", # escape (ESC)
2042 'v' => "\013", # vertical tab (VT)
2045 if ($seq =~ m/^[0-7]{1,3}$/) {
2046 # octal char sequence
2047 return chr(oct($seq));
2048 } elsif (exists $es{$seq}) {
2049 # C escape sequence, aka character escape code
2050 return $es{$seq};
2052 # quoted ordinary character
2053 return $seq;
2056 if ($str =~ m/^"(.*)"$/) {
2057 # needs unquoting
2058 $str = $1;
2059 $str =~ s/\\([^0-7]|[0-7]{1,3})/unq($1)/eg;
2061 return $str;
2064 # escape tabs (convert tabs to spaces)
2065 sub untabify {
2066 my $line = shift;
2068 while ((my $pos = index($line, "\t")) != -1) {
2069 if (my $count = (8 - ($pos % 8))) {
2070 my $spaces = ' ' x $count;
2071 $line =~ s/\t/$spaces/;
2075 return $line;
2078 sub project_in_list {
2079 my $project = shift;
2080 my @list = git_get_projects_list();
2081 return @list && scalar(grep { $_->{'path'} eq $project } @list);
2084 sub cached_page_precondition_check {
2085 my $action = shift;
2086 return 1 unless
2087 $action eq 'summary' &&
2088 $projlist_cache_lifetime > 0 &&
2089 gitweb_check_feature('forks');
2091 # Note that ALL the 'forkchange' logic is in this function.
2092 # It does NOT belong in cached_action_page NOR in cached_action_start
2093 # NOR in cached_action_finish. None of those functions should know anything
2094 # about nor do anything to any of the 'forkchange'/"$action.forkchange" files.
2096 # besides the basic 'changed' "$action.changed" check, we may only use
2097 # a summary cache if:
2099 # 1) we are not using a project list cache file
2100 # -OR-
2101 # 2) we are not using the 'forks' feature
2102 # -OR-
2103 # 3) there is no 'forkchange' nor "$action.forkchange" file in $html_cache_dir
2104 # -OR-
2105 # 4) there is no cache file ("$cache_dir/$projlist_cache_name")
2106 # -OR-
2107 # 5) the OLDER of 'forkchange'/"$action.forkchange" is NEWER than the cache file
2109 # Otherwise we must re-generate the cache because we've had a fork change
2110 # (either a fork was added or a fork was removed) AND the change has been
2111 # picked up in the cache file AND we've not got that in our cached copy
2113 # For (5) regenerating the cached page wouldn't get us anything if the project
2114 # cache file is older than the 'forkchange'/"$action.forkchange" because the
2115 # forks information comes from the project cache file and it's clearly not
2116 # picked up the changes yet so we may continue to use a cached page until it does.
2118 my $htmlcd = "$projectroot/$project/$html_cache_dir";
2119 my $fc_mt = (stat("$htmlcd/forkchange"))[9];
2120 my $afc_mt = (stat("$htmlcd/$action.forkchange"))[9];
2121 return 1 unless defined($fc_mt) || defined($afc_mt);
2122 my $prj_mt = (stat("$cache_dir/$projlist_cache_name"))[9];
2123 return 1 unless $prj_mt;
2124 my $old_mt = $fc_mt;
2125 $old_mt = $afc_mt if !defined($old_mt) || (defined($afc_mt) && $afc_mt < $old_mt);
2126 return 1 if $old_mt > $prj_mt;
2128 # We're going to regenerate the cached page because we know the project cache
2129 # has new fork information that we cannot possibly have in our cached copy.
2131 # However, if both 'forkchange' and "$action.forkchange" exist and one of
2132 # them is older than the project cache and one of them is newer, we still
2133 # need to regenerate the page cache, but we will also need to do it again
2134 # in the future because there's yet another fork update not yet in the cache.
2136 # So we make sure to touch "$action.changed" to force a cache regeneration
2137 # and then we remove either or both of 'forkchange'/"$action.forkchange" if
2138 # they're older than the project cache (they've served their purpose, we're
2139 # forcing a page regeneration by touching "$action.changed" but the project
2140 # cache was rebuilt since then so there are no more pending fork updates to
2141 # pick up in the future and they need to go).
2143 # For best results, the external code that touches 'forkchange' should always
2144 # touch 'forkchange' and additionally touch 'summary.forkchange' but only
2145 # if it does not already exist. That way the cached page will be regenerated
2146 # each time it's requested and ANY fork updates are available in the proj
2147 # cache rather than waiting until they all are before updating.
2149 # Note that we take a shortcut here and will zap 'forkchange' since we know
2150 # that it only affects the 'summary' cache. If, in the future, it affects
2151 # other cache types, it will first need to be propogated down to
2152 # "$action.forkchange" for those types before we zap it.
2154 my $fd;
2155 open $fd, '>', "$htmlcd/$action.changed" and close $fd;
2156 $fc_mt=undef, unlink "$htmlcd/forkchange" if defined $fc_mt && $fc_mt < $prj_mt;
2157 $afc_mt=undef, unlink "$htmlcd/$action.forkchange" if defined $afc_mt && $afc_mt < $prj_mt;
2159 # Now we propagate 'forkchange' to "$action.forkchange" if we have the
2160 # one and not the other.
2162 if (defined $fc_mt && ! defined $afc_mt) {
2163 open $fd, '>', "$htmlcd/$action.forkchange" and close $fd;
2164 -e "$htmlcd/$action.forkchange" and
2165 utime($fc_mt, $fc_mt, "$htmlcd/$action.forkchange") and
2166 unlink "$htmlcd/forkchange";
2169 return 0;
2172 sub cached_action_page {
2173 my $action = shift;
2175 return undef unless $action && $html_cache_actions{$action} && $html_cache_dir;
2176 my $htmlcd = "$projectroot/$project/$html_cache_dir";
2177 return undef if -e "$htmlcd/changed" || -e "$htmlcd/$action.changed";
2178 return undef unless cached_page_precondition_check($action);
2179 open my $fd, '<', "$htmlcd/$action" or return undef;
2180 binmode $fd;
2181 local $/;
2182 my $cached_page = <$fd>;
2183 close $fd or return undef;
2184 return $cached_page;
2187 package Git::Gitweb::CacheFile;
2189 sub TIEHANDLE {
2190 use POSIX qw(:fcntl_h);
2191 my $class = shift;
2192 my $cachefile = shift;
2194 sysopen(my $self, $cachefile, O_WRONLY|O_CREAT|O_EXCL, 0664)
2195 or return undef;
2196 $$self->{'cachefile'} = $cachefile;
2197 $$self->{'opened'} = 1;
2198 $$self->{'contents'} = '';
2199 return bless $self, $class;
2202 sub CLOSE {
2203 my $self = shift;
2204 if ($$self->{'opened'}) {
2205 $$self->{'opened'} = 0;
2206 my $result = close $self;
2207 unlink $$self->{'cachefile'} unless $result;
2208 return $result;
2210 return 0;
2213 sub DESTROY {
2214 my $self = shift;
2215 if ($$self->{'opened'}) {
2216 $self->CLOSE() and unlink $$self->{'cachefile'};
2220 sub PRINT {
2221 my $self = shift;
2222 @_ = (map {my $x=$_; utf8::encode($x); $x} @_) unless $fcgi_raw_mode;
2223 print $self @_ if $$self->{'opened'};
2224 $$self->{'contents'} .= join('', @_);
2225 return 1;
2228 sub PRINTF {
2229 my $self = shift;
2230 my $template = shift;
2231 return $self->PRINT(sprintf $template, @_);
2234 sub contents {
2235 my $self = shift;
2236 return $$self->{'contents'};
2239 package main;
2241 # Caller is responsible for preserving STDOUT beforehand if needed
2242 sub cached_action_start {
2243 my $action = shift;
2245 return undef unless $html_cache_actions{$action} && $html_cache_dir;
2246 my $htmlcd = "$projectroot/$project/$html_cache_dir";
2247 return undef unless -d $htmlcd;
2248 if (-e "$htmlcd/changed") {
2249 foreach my $cacheable (keys(%html_cache_actions)) {
2250 next unless $supported_cache_actions{$cacheable} &&
2251 $html_cache_actions{$cacheable};
2252 my $fd;
2253 open $fd, '>', "$htmlcd/$cacheable.changed"
2254 and close $fd;
2256 unlink "$htmlcd/changed";
2258 local *CACHEFILE;
2259 tie *CACHEFILE, 'Git::Gitweb::CacheFile', "$htmlcd/$action.lock" or return undef;
2260 *STDOUT = *CACHEFILE;
2261 unlink "$htmlcd/$action", "$htmlcd/$action.changed";
2262 return 1;
2265 # Caller is responsible for restoring STDOUT afterward if needed
2266 sub cached_action_finish {
2267 my $action = shift;
2269 use File::Spec;
2271 my $obj = tied *STDOUT;
2272 return undef unless ref($obj) eq 'Git::Gitweb::CacheFile';
2273 my $cached_page = $obj->contents;
2274 (my $result = close(STDOUT)) or warn "couldn't close cache file on STDOUT: $!";
2275 # Do not leave STDOUT file descriptor invalid!
2276 local *NULL;
2277 open(NULL, '>', File::Spec->devnull) or die "couldn't open NULL to devnull: $!";
2278 *STDOUT = *NULL;
2279 return $cached_page unless $result;
2280 my $htmlcd = "$projectroot/$project/$html_cache_dir";
2281 return $cached_page unless -d $htmlcd;
2282 unlink "$htmlcd/$action.lock" unless rename "$htmlcd/$action.lock", "$htmlcd/$action";
2283 return $cached_page;
2286 my %expand_pi_subs;
2287 BEGIN {%expand_pi_subs = (
2288 'age_string' => \&age_string,
2289 'age_string_date' => \&age_string_date,
2290 'age_string_age' => \&age_string_age,
2291 'compute_timed_interval' => \&compute_timed_interval,
2292 'compute_commands_count' => \&compute_commands_count,
2295 # Expands any <?gitweb...> processing instructions and returns the result
2296 sub expand_gitweb_pi {
2297 my $page = shift;
2298 $page .= '';
2299 my @time_now = gettimeofday();
2300 $page =~ s{<\?gitweb(?:\s+([^\s>]+)([^>]*))?\s*\?>}
2301 {defined($1) ?
2302 (ref($expand_pi_subs{$1}) eq 'CODE' ?
2303 $expand_pi_subs{$1}->(split(' ',$2), @time_now) :
2304 '') :
2305 '' }goes;
2306 return $page;
2309 ## ----------------------------------------------------------------------
2310 ## HTML aware string manipulation
2312 # Try to chop given string on a word boundary between position
2313 # $len and $len+$add_len. If there is no word boundary there,
2314 # chop at $len+$add_len. Do not chop if chopped part plus ellipsis
2315 # (marking chopped part) would be longer than given string.
2316 sub chop_str {
2317 my $str = shift;
2318 my $len = shift;
2319 my $add_len = shift || 10;
2320 my $where = shift || 'right'; # 'left' | 'center' | 'right'
2322 # Make sure perl knows it is utf8 encoded so we don't
2323 # cut in the middle of a utf8 multibyte char.
2324 $str = to_utf8($str);
2326 # allow only $len chars, but don't cut a word if it would fit in $add_len
2327 # if it doesn't fit, cut it if it's still longer than the dots we would add
2328 # remove chopped character entities entirely
2330 # when chopping in the middle, distribute $len into left and right part
2331 # return early if chopping wouldn't make string shorter
2332 if ($where eq 'center') {
2333 return $str if ($len + 5 >= length($str)); # filler is length 5
2334 $len = int($len/2);
2335 } else {
2336 return $str if ($len + 4 >= length($str)); # filler is length 4
2339 # regexps: ending and beginning with word part up to $add_len
2340 my $endre = qr/.{$len}\w{0,$add_len}/;
2341 my $begre = qr/\w{0,$add_len}.{$len}/;
2343 if ($where eq 'left') {
2344 $str =~ m/^(.*?)($begre)$/;
2345 my ($lead, $body) = ($1, $2);
2346 if (length($lead) > 4) {
2347 $lead = " ...";
2349 return "$lead$body";
2351 } elsif ($where eq 'center') {
2352 $str =~ m/^($endre)(.*)$/;
2353 my ($left, $str) = ($1, $2);
2354 $str =~ m/^(.*?)($begre)$/;
2355 my ($mid, $right) = ($1, $2);
2356 if (length($mid) > 5) {
2357 $mid = " ... ";
2359 return "$left$mid$right";
2361 } else {
2362 $str =~ m/^($endre)(.*)$/;
2363 my $body = $1;
2364 my $tail = $2;
2365 if (length($tail) > 4) {
2366 $tail = "... ";
2368 return "$body$tail";
2372 # pass-through email filter, obfuscating it when possible
2373 sub email_obfuscate {
2374 our $email;
2375 my ($str) = @_;
2376 if ($email) {
2377 $str = $email->escape_html($str);
2378 # Stock HTML::Email::Obfuscate version likes to produce
2379 # invalid XHTML...
2380 $str =~ s#<(/?)B>#<$1b>#g;
2381 return $str;
2382 } else {
2383 $str = esc_html($str);
2384 $str =~ s/@/&#x40;/;
2385 return $str;
2389 # takes the same arguments as chop_str, but also wraps a <span> around the
2390 # result with a title attribute if it does get chopped. Additionally, the
2391 # string is HTML-escaped.
2392 sub chop_and_escape_str {
2393 my ($str) = @_;
2395 my $chopped = chop_str(@_);
2396 $str = to_utf8($str);
2397 if ($chopped eq $str) {
2398 return email_obfuscate($chopped);
2399 } else {
2400 use bytes;
2401 $str =~ s/[[:cntrl:]]/?/g;
2402 return $cgi->span({-title=>$str}, email_obfuscate($chopped));
2406 # Highlight selected fragments of string, using given CSS class,
2407 # and escape HTML. It is assumed that fragments do not overlap.
2408 # Regions are passed as list of pairs (array references).
2410 # Example: esc_html_hl_regions("foobar", "mark", [ 0, 3 ]) returns
2411 # '<span class="mark">foo</span>bar'
2412 sub esc_html_hl_regions {
2413 my ($str, $css_class, @sel) = @_;
2414 my %opts = grep { ref($_) ne 'ARRAY' } @sel;
2415 @sel = grep { ref($_) eq 'ARRAY' } @sel;
2416 return esc_html($str, %opts) unless @sel;
2418 my $out = '';
2419 my $pos = 0;
2421 for my $s (@sel) {
2422 my ($begin, $end) = @$s;
2424 # Don't create empty <span> elements.
2425 next if $end <= $begin;
2427 my $escaped = esc_html(substr($str, $begin, $end - $begin),
2428 %opts);
2430 $out .= esc_html(substr($str, $pos, $begin - $pos), %opts)
2431 if ($begin - $pos > 0);
2432 $out .= $cgi->span({-class => $css_class}, $escaped);
2434 $pos = $end;
2436 $out .= esc_html(substr($str, $pos), %opts)
2437 if ($pos < length($str));
2439 return $out;
2442 # return positions of beginning and end of each match
2443 sub matchpos_list {
2444 my ($str, $regexp) = @_;
2445 return unless (defined $str && defined $regexp);
2447 my @matches;
2448 while ($str =~ /$regexp/g) {
2449 push @matches, [$-[0], $+[0]];
2451 return @matches;
2454 # highlight match (if any), and escape HTML
2455 sub esc_html_match_hl {
2456 my ($str, $regexp) = @_;
2457 return esc_html($str) unless defined $regexp;
2459 my @matches = matchpos_list($str, $regexp);
2460 return esc_html($str) unless @matches;
2462 return esc_html_hl_regions($str, 'match', @matches);
2466 # highlight match (if any) of shortened string, and escape HTML
2467 sub esc_html_match_hl_chopped {
2468 my ($str, $chopped, $regexp) = @_;
2469 return esc_html_match_hl($str, $regexp) unless defined $chopped;
2471 my @matches = matchpos_list($str, $regexp);
2472 return esc_html($chopped) unless @matches;
2474 # filter matches so that we mark chopped string
2475 my $tail = "... "; # see chop_str
2476 unless ($chopped =~ s/\Q$tail\E$//) {
2477 $tail = '';
2479 my $chop_len = length($chopped);
2480 my $tail_len = length($tail);
2481 my @filtered;
2483 for my $m (@matches) {
2484 if ($m->[0] > $chop_len) {
2485 push @filtered, [ $chop_len, $chop_len + $tail_len ] if ($tail_len > 0);
2486 last;
2487 } elsif ($m->[1] > $chop_len) {
2488 push @filtered, [ $m->[0], $chop_len + $tail_len ];
2489 last;
2491 push @filtered, $m;
2494 return esc_html_hl_regions($chopped . $tail, 'match', @filtered);
2497 ## ----------------------------------------------------------------------
2498 ## functions returning short strings
2500 # CSS class for given age epoch value (in seconds)
2501 # and reference time (optional, defaults to now) as second value
2502 sub age_class {
2503 my ($age_epoch, $time_now) = @_;
2504 return "noage" unless defined $age_epoch;
2505 defined $time_now or $time_now = time;
2506 my $age = $time_now - $age_epoch;
2508 if ($age < 60*60*2) {
2509 return "age0";
2510 } elsif ($age < 60*60*24*2) {
2511 return "age1";
2512 } else {
2513 return "age2";
2517 # convert age epoch in seconds to "nn units ago" string
2518 # reference time used is now unless second argument passed in
2519 # to get the old behavior, pass 0 as the first argument and
2520 # the time in seconds as the second
2521 sub age_string {
2522 my ($age_epoch, $time_now) = @_;
2523 return "unknown" unless defined $age_epoch;
2524 return "<?gitweb age_string $age_epoch?>" if $cache_mode_active;
2525 defined $time_now or $time_now = time;
2526 my $age = $time_now - $age_epoch;
2527 my $age_str;
2529 if ($age > 60*60*24*365*2) {
2530 $age_str = (int $age/60/60/24/365);
2531 $age_str .= " years ago";
2532 } elsif ($age > 60*60*24*(365/12)*2) {
2533 $age_str = int $age/60/60/24/(365/12);
2534 $age_str .= " months ago";
2535 } elsif ($age > 60*60*24*7*2) {
2536 $age_str = int $age/60/60/24/7;
2537 $age_str .= " weeks ago";
2538 } elsif ($age > 60*60*24*2) {
2539 $age_str = int $age/60/60/24;
2540 $age_str .= " days ago";
2541 } elsif ($age > 60*60*2) {
2542 $age_str = int $age/60/60;
2543 $age_str .= " hours ago";
2544 } elsif ($age > 60*2) {
2545 $age_str = int $age/60;
2546 $age_str .= " min ago";
2547 } elsif ($age > 2) {
2548 $age_str = int $age;
2549 $age_str .= " sec ago";
2550 } else {
2551 $age_str .= " right now";
2553 return $age_str;
2556 # returns age_string if the age is <= 2 weeks otherwise an absolute date
2557 # this is typically shown to the user directly with the age_string_age as a title
2558 sub age_string_date {
2559 my ($age_epoch, $time_now) = @_;
2560 return "unknown" unless defined $age_epoch;
2561 return "<?gitweb age_string_date $age_epoch?>" if $cache_mode_active;
2562 defined $time_now or $time_now = time;
2563 my $age = $time_now - $age_epoch;
2565 if ($age > 60*60*24*7*2) {
2566 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($age_epoch);
2567 return sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2568 } else {
2569 return age_string($age_epoch, $time_now);
2573 # returns an absolute date if the age is <= 2 weeks otherwise age_string
2574 # this is typically used for the 'title' attribute so it will show as a tooltip
2575 sub age_string_age {
2576 my ($age_epoch, $time_now) = @_;
2577 return "unknown" unless defined $age_epoch;
2578 return "<?gitweb age_string_age $age_epoch?>" if $cache_mode_active;
2579 defined $time_now or $time_now = time;
2580 my $age = $time_now - $age_epoch;
2582 if ($age > 60*60*24*7*2) {
2583 return age_string($age_epoch, $time_now);
2584 } else {
2585 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($age_epoch);
2586 return sprintf "%4i-%02u-%02i", 1900 + $year, $mon+1, $mday;
2590 use constant {
2591 S_IFINVALID => 0030000,
2592 S_IFGITLINK => 0160000,
2595 # submodule/subproject, a commit object reference
2596 sub S_ISGITLINK {
2597 my $mode = shift;
2599 return (($mode & S_IFMT) == S_IFGITLINK)
2602 # convert file mode in octal to symbolic file mode string
2603 sub mode_str {
2604 my $mode = oct shift;
2606 if (S_ISGITLINK($mode)) {
2607 return 'm---------';
2608 } elsif (S_ISDIR($mode & S_IFMT)) {
2609 return 'drwxr-xr-x';
2610 } elsif (S_ISLNK($mode)) {
2611 return 'lrwxrwxrwx';
2612 } elsif (S_ISREG($mode)) {
2613 # git cares only about the executable bit
2614 if ($mode & S_IXUSR) {
2615 return '-rwxr-xr-x';
2616 } else {
2617 return '-rw-r--r--';
2619 } else {
2620 return '----------';
2624 # convert file mode in octal to file type string
2625 sub file_type {
2626 my $mode = shift;
2628 if ($mode !~ m/^[0-7]+$/) {
2629 return $mode;
2630 } else {
2631 $mode = oct $mode;
2634 if (S_ISGITLINK($mode)) {
2635 return "submodule";
2636 } elsif (S_ISDIR($mode & S_IFMT)) {
2637 return "directory";
2638 } elsif (S_ISLNK($mode)) {
2639 return "symlink";
2640 } elsif (S_ISREG($mode)) {
2641 return "file";
2642 } else {
2643 return "unknown";
2647 # convert file mode in octal to file type description string
2648 sub file_type_long {
2649 my $mode = shift;
2651 if ($mode !~ m/^[0-7]+$/) {
2652 return $mode;
2653 } else {
2654 $mode = oct $mode;
2657 if (S_ISGITLINK($mode)) {
2658 return "submodule";
2659 } elsif (S_ISDIR($mode & S_IFMT)) {
2660 return "directory";
2661 } elsif (S_ISLNK($mode)) {
2662 return "symlink";
2663 } elsif (S_ISREG($mode)) {
2664 if ($mode & S_IXUSR) {
2665 return "executable";
2666 } else {
2667 return "file";
2669 } else {
2670 return "unknown";
2675 ## ----------------------------------------------------------------------
2676 ## functions returning short HTML fragments, or transforming HTML fragments
2677 ## which don't belong to other sections
2679 # format line of commit message.
2680 sub format_log_line_html {
2681 my $line = shift;
2683 $line = esc_html($line, -nbsp=>1);
2684 $line =~ s{\b([0-9a-fA-F]{8,40})\b}{
2685 $cgi->a({-href => href(action=>"object", hash=>$1),
2686 -class => "text"}, $1);
2687 }eg unless $line =~ /^\s*git-svn-id:/;
2689 return $line;
2692 # format marker of refs pointing to given object
2694 # the destination action is chosen based on object type and current context:
2695 # - for annotated tags, we choose the tag view unless it's the current view
2696 # already, in which case we go to shortlog view
2697 # - for other refs, we keep the current view if we're in history, shortlog or
2698 # log view, and select shortlog otherwise
2699 sub format_ref_marker {
2700 my ($refs, $id) = @_;
2701 my $markers = '';
2703 if (defined $refs->{$id}) {
2704 foreach my $ref (@{$refs->{$id}}) {
2705 # this code exploits the fact that non-lightweight tags are the
2706 # only indirect objects, and that they are the only objects for which
2707 # we want to use tag instead of shortlog as action
2708 my ($type, $name) = qw();
2709 my $indirect = ($ref =~ s/\^\{\}$//);
2710 # e.g. tags/v2.6.11 or heads/next
2711 if ($ref =~ m!^(.*?)s?/(.*)$!) {
2712 $type = $1;
2713 $name = $2;
2714 } else {
2715 $type = "ref";
2716 $name = $ref;
2719 my $class = $type;
2720 $class .= " indirect" if $indirect;
2722 my $dest_action = "shortlog";
2724 if ($indirect) {
2725 $dest_action = "tag" unless $action eq "tag";
2726 } elsif ($action =~ /^(history|(short)?log)$/) {
2727 $dest_action = $action;
2730 my $dest = "";
2731 $dest .= "refs/" unless $ref =~ m!^refs/!;
2732 $dest .= $ref;
2734 my $link = $cgi->a({
2735 -href => href(
2736 action=>$dest_action,
2737 hash=>$dest
2738 )}, $name);
2740 $markers .= "<span class=\"".esc_attr($class)."\" title=\"".esc_attr($ref)."\">" .
2741 $link . "</span>";
2745 if ($markers) {
2746 return '<span class="refs">'. $markers . '</span>';
2747 } else {
2748 return "";
2752 # format, perhaps shortened and with markers, title line
2753 sub format_subject_html {
2754 my ($long, $short, $href, $extra) = @_;
2755 $extra = '' unless defined($extra);
2757 if (length($short) < length($long)) {
2758 use bytes;
2759 $long =~ s/[[:cntrl:]]/?/g;
2760 return $cgi->a({-href => $href, -class => "list subject",
2761 -title => to_utf8($long)},
2762 esc_html($short)) . $extra;
2763 } else {
2764 return $cgi->a({-href => $href, -class => "list subject"},
2765 esc_html($long)) . $extra;
2769 # Rather than recomputing the url for an email multiple times, we cache it
2770 # after the first hit. This gives a visible benefit in views where the avatar
2771 # for the same email is used repeatedly (e.g. shortlog).
2772 # The cache is shared by all avatar engines (currently gravatar only), which
2773 # are free to use it as preferred. Since only one avatar engine is used for any
2774 # given page, there's no risk for cache conflicts.
2775 our %avatar_cache = ();
2777 # Compute the picon url for a given email, by using the picon search service over at
2778 # http://www.cs.indiana.edu/picons/search.html
2779 sub picon_url {
2780 my $email = lc shift;
2781 if (!$avatar_cache{$email}) {
2782 my ($user, $domain) = split('@', $email);
2783 $avatar_cache{$email} =
2784 "//www.cs.indiana.edu/cgi-pub/kinzler/piconsearch.cgi/" .
2785 "$domain/$user/" .
2786 "users+domains+unknown/up/single";
2788 return $avatar_cache{$email};
2791 # Compute the gravatar url for a given email, if it's not in the cache already.
2792 # Gravatar stores only the part of the URL before the size, since that's the
2793 # one computationally more expensive. This also allows reuse of the cache for
2794 # different sizes (for this particular engine).
2795 sub gravatar_url {
2796 my $email = lc shift;
2797 my $size = shift;
2798 $avatar_cache{$email} ||=
2799 "//www.gravatar.com/avatar/" .
2800 Digest::MD5::md5_hex($email) . "?s=";
2801 return $avatar_cache{$email} . $size;
2804 # Insert an avatar for the given $email at the given $size if the feature
2805 # is enabled.
2806 sub git_get_avatar {
2807 my ($email, %opts) = @_;
2808 my $pre_white = ($opts{-pad_before} ? "&#160;" : "");
2809 my $post_white = ($opts{-pad_after} ? "&#160;" : "");
2810 $opts{-size} ||= 'default';
2811 my $size = $avatar_size{$opts{-size}} || $avatar_size{'default'};
2812 my $url = "";
2813 if ($git_avatar eq 'gravatar') {
2814 $url = gravatar_url($email, $size);
2815 } elsif ($git_avatar eq 'picon') {
2816 $url = picon_url($email);
2818 # Other providers can be added by extending the if chain, defining $url
2819 # as needed. If no variant puts something in $url, we assume avatars
2820 # are completely disabled/unavailable.
2821 if ($url) {
2822 return $pre_white .
2823 "<img width=\"$size\" " .
2824 "class=\"avatar\" " .
2825 "src=\"".esc_url($url)."\" " .
2826 "alt=\"\" " .
2827 "/>" . $post_white;
2828 } else {
2829 return "";
2833 sub format_search_author {
2834 my ($author, $searchtype, $displaytext) = @_;
2835 my $have_search = gitweb_check_feature('search');
2837 if ($have_search) {
2838 my $performed = "";
2839 if ($searchtype eq 'author') {
2840 $performed = "authored";
2841 } elsif ($searchtype eq 'committer') {
2842 $performed = "committed";
2845 return $cgi->a({-href => href(action=>"search", hash=>$hash,
2846 searchtext=>$author,
2847 searchtype=>$searchtype), class=>"list",
2848 title=>"Search for commits $performed by $author"},
2849 $displaytext);
2851 } else {
2852 return $displaytext;
2856 # format the author name of the given commit with the given tag
2857 # the author name is chopped and escaped according to the other
2858 # optional parameters (see chop_str).
2859 sub format_author_html {
2860 my $tag = shift;
2861 my $co = shift;
2862 my $author = chop_and_escape_str($co->{'author_name'}, @_);
2863 return "<$tag class=\"author\">" .
2864 format_search_author($co->{'author_name'}, "author",
2865 git_get_avatar($co->{'author_email'}, -pad_after => 1) .
2866 $author) .
2867 "</$tag>";
2870 # format git diff header line, i.e. "diff --(git|combined|cc) ..."
2871 sub format_git_diff_header_line {
2872 my $line = shift;
2873 my $diffinfo = shift;
2874 my ($from, $to) = @_;
2876 if ($diffinfo->{'nparents'}) {
2877 # combined diff
2878 $line =~ s!^(diff (.*?) )"?.*$!$1!;
2879 if ($to->{'href'}) {
2880 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2881 esc_path($to->{'file'}));
2882 } else { # file was deleted (no href)
2883 $line .= esc_path($to->{'file'});
2885 } else {
2886 # "ordinary" diff
2887 $line =~ s!^(diff (.*?) )"?a/.*$!$1!;
2888 if ($from->{'href'}) {
2889 $line .= $cgi->a({-href => $from->{'href'}, -class => "path"},
2890 'a/' . esc_path($from->{'file'}));
2891 } else { # file was added (no href)
2892 $line .= 'a/' . esc_path($from->{'file'});
2894 $line .= ' ';
2895 if ($to->{'href'}) {
2896 $line .= $cgi->a({-href => $to->{'href'}, -class => "path"},
2897 'b/' . esc_path($to->{'file'}));
2898 } else { # file was deleted
2899 $line .= 'b/' . esc_path($to->{'file'});
2903 return "<div class=\"diff header\">$line</div>\n";
2906 # format extended diff header line, before patch itself
2907 sub format_extended_diff_header_line {
2908 my $line = shift;
2909 my $diffinfo = shift;
2910 my ($from, $to) = @_;
2912 # match <path>
2913 if ($line =~ s!^((copy|rename) from ).*$!$1! && $from->{'href'}) {
2914 $line .= $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2915 esc_path($from->{'file'}));
2917 if ($line =~ s!^((copy|rename) to ).*$!$1! && $to->{'href'}) {
2918 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"path"},
2919 esc_path($to->{'file'}));
2921 # match single <mode>
2922 if ($line =~ m/\s(\d{6})$/) {
2923 $line .= '<span class="info"> (' .
2924 file_type_long($1) .
2925 ')</span>';
2927 # match <hash>
2928 if ($line =~ m/^index [0-9a-fA-F]{40},[0-9a-fA-F]{40}/) {
2929 # can match only for combined diff
2930 $line = 'index ';
2931 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2932 if ($from->{'href'}[$i]) {
2933 $line .= $cgi->a({-href=>$from->{'href'}[$i],
2934 -class=>"hash"},
2935 substr($diffinfo->{'from_id'}[$i],0,7));
2936 } else {
2937 $line .= '0' x 7;
2939 # separator
2940 $line .= ',' if ($i < $diffinfo->{'nparents'} - 1);
2942 $line .= '..';
2943 if ($to->{'href'}) {
2944 $line .= $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2945 substr($diffinfo->{'to_id'},0,7));
2946 } else {
2947 $line .= '0' x 7;
2950 } elsif ($line =~ m/^index [0-9a-fA-F]{40}..[0-9a-fA-F]{40}/) {
2951 # can match only for ordinary diff
2952 my ($from_link, $to_link);
2953 if ($from->{'href'}) {
2954 $from_link = $cgi->a({-href=>$from->{'href'}, -class=>"hash"},
2955 substr($diffinfo->{'from_id'},0,7));
2956 } else {
2957 $from_link = '0' x 7;
2959 if ($to->{'href'}) {
2960 $to_link = $cgi->a({-href=>$to->{'href'}, -class=>"hash"},
2961 substr($diffinfo->{'to_id'},0,7));
2962 } else {
2963 $to_link = '0' x 7;
2965 my ($from_id, $to_id) = ($diffinfo->{'from_id'}, $diffinfo->{'to_id'});
2966 $line =~ s!$from_id\.\.$to_id!$from_link..$to_link!;
2969 return $line . "<br/>\n";
2972 # format from-file/to-file diff header
2973 sub format_diff_from_to_header {
2974 my ($from_line, $to_line, $diffinfo, $from, $to, @parents) = @_;
2975 my $line;
2976 my $result = '';
2978 $line = $from_line;
2979 #assert($line =~ m/^---/) if DEBUG;
2980 # no extra formatting for "^--- /dev/null"
2981 if (! $diffinfo->{'nparents'}) {
2982 # ordinary (single parent) diff
2983 if ($line =~ m!^--- "?a/!) {
2984 if ($from->{'href'}) {
2985 $line = '--- a/' .
2986 $cgi->a({-href=>$from->{'href'}, -class=>"path"},
2987 esc_path($from->{'file'}));
2988 } else {
2989 $line = '--- a/' .
2990 esc_path($from->{'file'});
2993 $result .= qq!<div class="diff from_file">$line</div>\n!;
2995 } else {
2996 # combined diff (merge commit)
2997 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
2998 if ($from->{'href'}[$i]) {
2999 $line = '--- ' .
3000 $cgi->a({-href=>href(action=>"blobdiff",
3001 hash_parent=>$diffinfo->{'from_id'}[$i],
3002 hash_parent_base=>$parents[$i],
3003 file_parent=>$from->{'file'}[$i],
3004 hash=>$diffinfo->{'to_id'},
3005 hash_base=>$hash,
3006 file_name=>$to->{'file'}),
3007 -class=>"path",
3008 -title=>"diff" . ($i+1)},
3009 $i+1) .
3010 '/' .
3011 $cgi->a({-href=>$from->{'href'}[$i], -class=>"path"},
3012 esc_path($from->{'file'}[$i]));
3013 } else {
3014 $line = '--- /dev/null';
3016 $result .= qq!<div class="diff from_file">$line</div>\n!;
3020 $line = $to_line;
3021 #assert($line =~ m/^\+\+\+/) if DEBUG;
3022 # no extra formatting for "^+++ /dev/null"
3023 if ($line =~ m!^\+\+\+ "?b/!) {
3024 if ($to->{'href'}) {
3025 $line = '+++ b/' .
3026 $cgi->a({-href=>$to->{'href'}, -class=>"path"},
3027 esc_path($to->{'file'}));
3028 } else {
3029 $line = '+++ b/' .
3030 esc_path($to->{'file'});
3033 $result .= qq!<div class="diff to_file">$line</div>\n!;
3035 return $result;
3038 # create note for patch simplified by combined diff
3039 sub format_diff_cc_simplified {
3040 my ($diffinfo, @parents) = @_;
3041 my $result = '';
3043 $result .= "<div class=\"diff header\">" .
3044 "diff --cc ";
3045 if (!is_deleted($diffinfo)) {
3046 $result .= $cgi->a({-href => href(action=>"blob",
3047 hash_base=>$hash,
3048 hash=>$diffinfo->{'to_id'},
3049 file_name=>$diffinfo->{'to_file'}),
3050 -class => "path"},
3051 esc_path($diffinfo->{'to_file'}));
3052 } else {
3053 $result .= esc_path($diffinfo->{'to_file'});
3055 $result .= "</div>\n" . # class="diff header"
3056 "<div class=\"diff nodifferences\">" .
3057 "Simple merge" .
3058 "</div>\n"; # class="diff nodifferences"
3060 return $result;
3063 sub diff_line_class {
3064 my ($line, $from, $to) = @_;
3066 # ordinary diff
3067 my $num_sign = 1;
3068 # combined diff
3069 if ($from && $to && ref($from->{'href'}) eq "ARRAY") {
3070 $num_sign = scalar @{$from->{'href'}};
3073 my @diff_line_classifier = (
3074 { regexp => qr/^\@\@{$num_sign} /, class => "chunk_header"},
3075 { regexp => qr/^\\/, class => "incomplete" },
3076 { regexp => qr/^ {$num_sign}/, class => "ctx" },
3077 # classifier for context must come before classifier add/rem,
3078 # or we would have to use more complicated regexp, for example
3079 # qr/(?= {0,$m}\+)[+ ]{$num_sign}/, where $m = $num_sign - 1;
3080 { regexp => qr/^[+ ]{$num_sign}/, class => "add" },
3081 { regexp => qr/^[- ]{$num_sign}/, class => "rem" },
3083 for my $clsfy (@diff_line_classifier) {
3084 return $clsfy->{'class'}
3085 if ($line =~ $clsfy->{'regexp'});
3088 # fallback
3089 return "";
3092 # assumes that $from and $to are defined and correctly filled,
3093 # and that $line holds a line of chunk header for unified diff
3094 sub format_unidiff_chunk_header {
3095 my ($line, $from, $to) = @_;
3097 my ($from_text, $from_start, $from_lines, $to_text, $to_start, $to_lines, $section) =
3098 $line =~ m/^\@{2} (-(\d+)(?:,(\d+))?) (\+(\d+)(?:,(\d+))?) \@{2}(.*)$/;
3100 $from_lines = 0 unless defined $from_lines;
3101 $to_lines = 0 unless defined $to_lines;
3103 if ($from->{'href'}) {
3104 $from_text = $cgi->a({-href=>"$from->{'href'}#l$from_start",
3105 -class=>"list"}, $from_text);
3107 if ($to->{'href'}) {
3108 $to_text = $cgi->a({-href=>"$to->{'href'}#l$to_start",
3109 -class=>"list"}, $to_text);
3111 $line = "<span class=\"chunk_info\">@@ $from_text $to_text @@</span>" .
3112 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
3113 return $line;
3116 # assumes that $from and $to are defined and correctly filled,
3117 # and that $line holds a line of chunk header for combined diff
3118 sub format_cc_diff_chunk_header {
3119 my ($line, $from, $to) = @_;
3121 my ($prefix, $ranges, $section) = $line =~ m/^(\@+) (.*?) \@+(.*)$/;
3122 my (@from_text, @from_start, @from_nlines, $to_text, $to_start, $to_nlines);
3124 @from_text = split(' ', $ranges);
3125 for (my $i = 0; $i < @from_text; ++$i) {
3126 ($from_start[$i], $from_nlines[$i]) =
3127 (split(',', substr($from_text[$i], 1)), 0);
3130 $to_text = pop @from_text;
3131 $to_start = pop @from_start;
3132 $to_nlines = pop @from_nlines;
3134 $line = "<span class=\"chunk_info\">$prefix ";
3135 for (my $i = 0; $i < @from_text; ++$i) {
3136 if ($from->{'href'}[$i]) {
3137 $line .= $cgi->a({-href=>"$from->{'href'}[$i]#l$from_start[$i]",
3138 -class=>"list"}, $from_text[$i]);
3139 } else {
3140 $line .= $from_text[$i];
3142 $line .= " ";
3144 if ($to->{'href'}) {
3145 $line .= $cgi->a({-href=>"$to->{'href'}#l$to_start",
3146 -class=>"list"}, $to_text);
3147 } else {
3148 $line .= $to_text;
3150 $line .= " $prefix</span>" .
3151 "<span class=\"section\">" . esc_html($section, -nbsp=>1) . "</span>";
3152 return $line;
3155 # process patch (diff) line (not to be used for diff headers),
3156 # returning HTML-formatted (but not wrapped) line.
3157 # If the line is passed as a reference, it is treated as HTML and not
3158 # esc_html()'ed.
3159 sub format_diff_line {
3160 my ($line, $diff_class, $from, $to) = @_;
3162 if (ref($line)) {
3163 $line = $$line;
3164 } else {
3165 chomp $line;
3166 $line = untabify($line);
3168 if ($from && $to && $line =~ m/^\@{2} /) {
3169 $line = format_unidiff_chunk_header($line, $from, $to);
3170 } elsif ($from && $to && $line =~ m/^\@{3}/) {
3171 $line = format_cc_diff_chunk_header($line, $from, $to);
3172 } else {
3173 $line = esc_html($line, -nbsp=>1);
3177 my $diff_classes = "diff diff_body";
3178 $diff_classes .= " $diff_class" if ($diff_class);
3179 $line = "<div class=\"$diff_classes\">$line</div>\n";
3181 return $line;
3184 # Generates undef or something like "_snapshot_" or "snapshot (_tbz2_ _zip_)",
3185 # linked. Pass the hash of the tree/commit to snapshot.
3186 sub format_snapshot_links {
3187 my ($hash) = @_;
3188 my $num_fmts = @snapshot_fmts;
3189 if ($num_fmts > 1) {
3190 # A parenthesized list of links bearing format names.
3191 # e.g. "snapshot (_tar.gz_ _zip_)"
3192 return "snapshot (" . join(' ', map
3193 $cgi->a({
3194 -href => href(
3195 action=>"snapshot",
3196 hash=>$hash,
3197 snapshot_format=>$_
3199 }, $known_snapshot_formats{$_}{'display'})
3200 , @snapshot_fmts) . ")";
3201 } elsif ($num_fmts == 1) {
3202 # A single "snapshot" link whose tooltip bears the format name.
3203 # i.e. "_snapshot_"
3204 my ($fmt) = @snapshot_fmts;
3205 return
3206 $cgi->a({
3207 -href => href(
3208 action=>"snapshot",
3209 hash=>$hash,
3210 snapshot_format=>$fmt
3212 -title => "in format: $known_snapshot_formats{$fmt}{'display'}"
3213 }, "snapshot");
3214 } else { # $num_fmts == 0
3215 return undef;
3219 ## ......................................................................
3220 ## functions returning values to be passed, perhaps after some
3221 ## transformation, to other functions; e.g. returning arguments to href()
3223 # returns hash to be passed to href to generate gitweb URL
3224 # in -title key it returns description of link
3225 sub get_feed_info {
3226 my $format = shift || 'Atom';
3227 my %res = (action => lc($format));
3228 my $matched_ref = 0;
3230 # feed links are possible only for project views
3231 return unless (defined $project);
3232 # some views should link to OPML, or to generic project feed,
3233 # or don't have specific feed yet (so they should use generic)
3234 return if (!$action || $action =~ /^(?:tags|heads|forks|tag|search)$/x);
3236 my $branch = undef;
3237 # branches refs uses 'refs/' + $get_branch_refs()[x] + '/' prefix
3238 # (fullname) to differentiate from tag links; this also makes
3239 # possible to detect branch links
3240 for my $ref (get_branch_refs()) {
3241 if ((defined $hash_base && $hash_base =~ m!^refs/\Q$ref\E/(.*)$!) ||
3242 (defined $hash && $hash =~ m!^refs/\Q$ref\E/(.*)$!)) {
3243 $branch = $1;
3244 $matched_ref = $ref;
3245 last;
3248 # find log type for feed description (title)
3249 my $type = 'log';
3250 if (defined $file_name) {
3251 $type = "history of $file_name";
3252 $type .= "/" if ($action eq 'tree');
3253 $type .= " on '$branch'" if (defined $branch);
3254 } else {
3255 $type = "log of $branch" if (defined $branch);
3258 $res{-title} = $type;
3259 $res{'hash'} = (defined $branch ? "refs/$matched_ref/$branch" : undef);
3260 $res{'file_name'} = $file_name;
3262 return %res;
3265 ## ----------------------------------------------------------------------
3266 ## git utility subroutines, invoking git commands
3268 # returns path to the core git executable and the --git-dir parameter as list
3269 sub git_cmd {
3270 $number_of_git_cmds++;
3271 return $GIT, '--git-dir='.$git_dir;
3274 # opens a "-|" cmd pipe handle with 2>/dev/null and returns it
3275 sub cmd_pipe {
3277 # In order to be compatible with FCGI mode we must use POSIX
3278 # and access the STDERR_FILENO file descriptor directly
3280 use POSIX qw(STDERR_FILENO dup dup2);
3282 open(my $null, '>', File::Spec->devnull) or die "couldn't open devnull: $!";
3283 (my $saveerr = dup(STDERR_FILENO)) or die "couldn't dup STDERR: $!";
3284 my $dup2ok = dup2(fileno($null), STDERR_FILENO);
3285 close($null) or !$dup2ok or die "couldn't close NULL: $!";
3286 $dup2ok or POSIX::close($saveerr), die "couldn't dup NULL to STDERR: $!";
3287 my $result = open(my $fd, "-|", @_);
3288 $dup2ok = dup2($saveerr, STDERR_FILENO);
3289 POSIX::close($saveerr) or !$dup2ok or die "couldn't close SAVEERR: $!";
3290 $dup2ok or die "couldn't dup SAVERR to STDERR: $!";
3292 return $result ? $fd : undef;
3295 # opens a "-|" git_cmd pipe handle with 2>/dev/null and returns it
3296 sub git_cmd_pipe {
3297 return cmd_pipe git_cmd(), @_;
3300 # quote the given arguments for passing them to the shell
3301 # quote_command("command", "arg 1", "arg with ' and ! characters")
3302 # => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
3303 # Try to avoid using this function wherever possible.
3304 sub quote_command {
3305 return join(' ',
3306 map { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ );
3309 # get HEAD ref of given project as hash
3310 sub git_get_head_hash {
3311 return git_get_full_hash(shift, 'HEAD');
3314 sub git_get_full_hash {
3315 return git_get_hash(@_);
3318 sub git_get_short_hash {
3319 return git_get_hash(@_, '--short=7');
3322 sub git_get_hash {
3323 my ($project, $hash, @options) = @_;
3324 my $o_git_dir = $git_dir;
3325 my $retval = undef;
3326 $git_dir = "$projectroot/$project";
3327 if (defined(my $fd = git_cmd_pipe 'rev-parse',
3328 '--verify', '-q', @options, $hash)) {
3329 $retval = <$fd>;
3330 chomp $retval if defined $retval;
3331 close $fd;
3333 if (defined $o_git_dir) {
3334 $git_dir = $o_git_dir;
3336 return $retval;
3339 # get type of given object
3340 sub git_get_type {
3341 my $hash = shift;
3343 defined(my $fd = git_cmd_pipe "cat-file", '-t', $hash) or return;
3344 my $type = <$fd>;
3345 close $fd or return;
3346 chomp $type;
3347 return $type;
3350 # repository configuration
3351 our $config_file = '';
3352 our %config;
3354 # store multiple values for single key as anonymous array reference
3355 # single values stored directly in the hash, not as [ <value> ]
3356 sub hash_set_multi {
3357 my ($hash, $key, $value) = @_;
3359 if (!exists $hash->{$key}) {
3360 $hash->{$key} = $value;
3361 } elsif (!ref $hash->{$key}) {
3362 $hash->{$key} = [ $hash->{$key}, $value ];
3363 } else {
3364 push @{$hash->{$key}}, $value;
3368 # return hash of git project configuration
3369 # optionally limited to some section, e.g. 'gitweb'
3370 sub git_parse_project_config {
3371 my $section_regexp = shift;
3372 my %config;
3374 local $/ = "\0";
3376 defined(my $fh = git_cmd_pipe "config", '-z', '-l')
3377 or return;
3379 while (my $keyval = to_utf8(scalar <$fh>)) {
3380 chomp $keyval;
3381 my ($key, $value) = split(/\n/, $keyval, 2);
3383 hash_set_multi(\%config, $key, $value)
3384 if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
3386 close $fh;
3388 return %config;
3391 # convert config value to boolean: 'true' or 'false'
3392 # no value, number > 0, 'true' and 'yes' values are true
3393 # rest of values are treated as false (never as error)
3394 sub config_to_bool {
3395 my $val = shift;
3397 return 1 if !defined $val; # section.key
3399 # strip leading and trailing whitespace
3400 $val =~ s/^\s+//;
3401 $val =~ s/\s+$//;
3403 return (($val =~ /^\d+$/ && $val) || # section.key = 1
3404 ($val =~ /^(?:true|yes)$/i)); # section.key = true
3407 # convert config value to simple decimal number
3408 # an optional value suffix of 'k', 'm', or 'g' will cause the value
3409 # to be multiplied by 1024, 1048576, or 1073741824
3410 sub config_to_int {
3411 my $val = shift;
3413 # strip leading and trailing whitespace
3414 $val =~ s/^\s+//;
3415 $val =~ s/\s+$//;
3417 if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
3418 $unit = lc($unit);
3419 # unknown unit is treated as 1
3420 return $num * ($unit eq 'g' ? 1073741824 :
3421 $unit eq 'm' ? 1048576 :
3422 $unit eq 'k' ? 1024 : 1);
3424 return $val;
3427 # convert config value to array reference, if needed
3428 sub config_to_multi {
3429 my $val = shift;
3431 return ref($val) ? $val : (defined($val) ? [ $val ] : []);
3434 sub git_get_project_config {
3435 my ($key, $type) = @_;
3437 return unless defined $git_dir;
3439 # key sanity check
3440 return unless ($key);
3441 # only subsection, if exists, is case sensitive,
3442 # and not lowercased by 'git config -z -l'
3443 if (my ($hi, $mi, $lo) = ($key =~ /^([^.]*)\.(.*)\.([^.]*)$/)) {
3444 $lo =~ s/_//g;
3445 $key = join(".", lc($hi), $mi, lc($lo));
3446 return if ($lo =~ /\W/ || $hi =~ /\W/);
3447 } else {
3448 $key = lc($key);
3449 $key =~ s/_//g;
3450 return if ($key =~ /\W/);
3452 $key =~ s/^gitweb\.//;
3454 # type sanity check
3455 if (defined $type) {
3456 $type =~ s/^--//;
3457 $type = undef
3458 unless ($type eq 'bool' || $type eq 'int');
3461 # get config
3462 if (!defined $config_file ||
3463 $config_file ne "$git_dir/config") {
3464 %config = git_parse_project_config('gitweb');
3465 $config_file = "$git_dir/config";
3468 # check if config variable (key) exists
3469 return unless exists $config{"gitweb.$key"};
3471 # ensure given type
3472 if (!defined $type) {
3473 return $config{"gitweb.$key"};
3474 } elsif ($type eq 'bool') {
3475 # backward compatibility: 'git config --bool' returns true/false
3476 return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
3477 } elsif ($type eq 'int') {
3478 return config_to_int($config{"gitweb.$key"});
3480 return $config{"gitweb.$key"};
3483 # get hash of given path at given ref
3484 sub git_get_hash_by_path {
3485 my $base = shift;
3486 my $path = shift || return undef;
3487 my $type = shift;
3489 $path =~ s,/+$,,;
3491 defined(my $fd = git_cmd_pipe "ls-tree", $base, "--", $path)
3492 or die_error(500, "Open git-ls-tree failed");
3493 my $line = to_utf8(scalar <$fd>);
3494 close $fd or return undef;
3496 if (!defined $line) {
3497 # there is no tree or hash given by $path at $base
3498 return undef;
3501 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
3502 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
3503 if (defined $type && $type ne $2) {
3504 # type doesn't match
3505 return undef;
3507 return $3;
3510 # get path of entry with given hash at given tree-ish (ref)
3511 # used to get 'from' filename for combined diff (merge commit) for renames
3512 sub git_get_path_by_hash {
3513 my $base = shift || return;
3514 my $hash = shift || return;
3516 local $/ = "\0";
3518 defined(my $fd = git_cmd_pipe "ls-tree", '-r', '-t', '-z', $base)
3519 or return undef;
3520 while (my $line = to_utf8(scalar <$fd>)) {
3521 chomp $line;
3523 #'040000 tree 595596a6a9117ddba9fe379b6b012b558bac8423 gitweb'
3524 #'100644 blob e02e90f0429be0d2a69b76571101f20b8f75530f gitweb/README'
3525 if ($line =~ m/(?:[0-9]+) (?:.+) $hash\t(.+)$/) {
3526 close $fd;
3527 return $1;
3530 close $fd;
3531 return undef;
3534 ## ......................................................................
3535 ## git utility functions, directly accessing git repository
3537 # get the value of config variable either from file named as the variable
3538 # itself in the repository ($GIT_DIR/$name file), or from gitweb.$name
3539 # configuration variable in the repository config file.
3540 sub git_get_file_or_project_config {
3541 my ($path, $name) = @_;
3543 $git_dir = "$projectroot/$path";
3544 open my $fd, '<', "$git_dir/$name"
3545 or return git_get_project_config($name);
3546 my $conf = to_utf8(scalar <$fd>);
3547 close $fd;
3548 if (defined $conf) {
3549 chomp $conf;
3551 return $conf;
3554 sub git_get_project_description {
3555 my $path = shift;
3556 return git_get_file_or_project_config($path, 'description');
3559 sub git_get_project_category {
3560 my $path = shift;
3561 return git_get_file_or_project_config($path, 'category');
3565 # supported formats:
3566 # * $GIT_DIR/ctags/<tagname> file (in 'ctags' subdirectory)
3567 # - if its contents is a number, use it as tag weight,
3568 # - otherwise add a tag with weight 1
3569 # * $GIT_DIR/ctags file, each line is a tag (with weight 1)
3570 # the same value multiple times increases tag weight
3571 # * `gitweb.ctag' multi-valued repo config variable
3572 sub git_get_project_ctags {
3573 my $project = shift;
3574 my $ctags = {};
3576 $git_dir = "$projectroot/$project";
3577 if (opendir my $dh, "$git_dir/ctags") {
3578 my @files = grep { -f $_ } map { "$git_dir/ctags/$_" } readdir($dh);
3579 foreach my $tagfile (@files) {
3580 open my $ct, '<', $tagfile
3581 or next;
3582 my $val = <$ct>;
3583 chomp $val if $val;
3584 close $ct;
3586 (my $ctag = $tagfile) =~ s#.*/##;
3587 $ctag = to_utf8($ctag);
3588 if ($val =~ /^\d+$/) {
3589 $ctags->{$ctag} = $val;
3590 } else {
3591 $ctags->{$ctag} = 1;
3594 closedir $dh;
3596 } elsif (open my $fh, '<', "$git_dir/ctags") {
3597 while (my $line = to_utf8(scalar <$fh>)) {
3598 chomp $line;
3599 $ctags->{$line}++ if $line;
3601 close $fh;
3603 } else {
3604 my $taglist = config_to_multi(git_get_project_config('ctag'));
3605 foreach my $tag (@$taglist) {
3606 $ctags->{$tag}++;
3610 return $ctags;
3613 # return hash, where keys are content tags ('ctags'),
3614 # and values are sum of weights of given tag in every project
3615 sub git_gather_all_ctags {
3616 my $projects = shift;
3617 my $ctags = {};
3619 foreach my $p (@$projects) {
3620 foreach my $ct (keys %{$p->{'ctags'}}) {
3621 $ctags->{$ct} += $p->{'ctags'}->{$ct};
3625 return $ctags;
3628 sub git_populate_project_tagcloud {
3629 my ($ctags, $action) = @_;
3631 # First, merge different-cased tags; tags vote on casing
3632 my %ctags_lc;
3633 foreach (keys %$ctags) {
3634 $ctags_lc{lc $_}->{count} += $ctags->{$_};
3635 if (not $ctags_lc{lc $_}->{topcount}
3636 or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) {
3637 $ctags_lc{lc $_}->{topcount} = $ctags->{$_};
3638 $ctags_lc{lc $_}->{topname} = $_;
3642 my $cloud;
3643 my $matched = $input_params{'ctag_filter'};
3644 if (eval { require HTML::TagCloud; 1; }) {
3645 $cloud = HTML::TagCloud->new;
3646 foreach my $ctag (sort keys %ctags_lc) {
3647 # Pad the title with spaces so that the cloud looks
3648 # less crammed.
3649 my $title = esc_html($ctags_lc{$ctag}->{topname});
3650 $title =~ s/ /&#160;/g;
3651 $title =~ s/^/&#160;/g;
3652 $title =~ s/$/&#160;/g;
3653 if (defined $matched && $matched eq $ctag) {
3654 $title = qq(<span class="match">$title</span>);
3656 $cloud->add($title, href(-replay=>1, action=>$action, ctag_filter=>$ctag),
3657 $ctags_lc{$ctag}->{count});
3659 } else {
3660 $cloud = {};
3661 foreach my $ctag (keys %ctags_lc) {
3662 my $title = esc_html($ctags_lc{$ctag}->{topname}, -nbsp=>1);
3663 if (defined $matched && $matched eq $ctag) {
3664 $title = qq(<span class="match">$title</span>);
3666 $cloud->{$ctag}{count} = $ctags_lc{$ctag}->{count};
3667 $cloud->{$ctag}{ctag} =
3668 $cgi->a({-href=>href(-replay=>1, action=>$action, ctag_filter=>$ctag)}, $title);
3671 return $cloud;
3674 sub git_show_project_tagcloud {
3675 my ($cloud, $count) = @_;
3676 if (ref $cloud eq 'HTML::TagCloud') {
3677 return $cloud->html_and_css($count);
3678 } else {
3679 my @tags = sort { $cloud->{$a}->{'count'} <=> $cloud->{$b}->{'count'} } keys %$cloud;
3680 return
3681 '<div id="htmltagcloud"'.($project ? '' : ' align="center"').'>' .
3682 join (', ', map {
3683 $cloud->{$_}->{'ctag'}
3684 } splice(@tags, 0, $count)) .
3685 '</div>';
3689 sub git_get_project_url_list {
3690 my $path = shift;
3692 $git_dir = "$projectroot/$path";
3693 open my $fd, '<', "$git_dir/cloneurl"
3694 or return wantarray ?
3695 @{ config_to_multi(git_get_project_config('url')) } :
3696 config_to_multi(git_get_project_config('url'));
3697 my @git_project_url_list = map { chomp; to_utf8($_) } <$fd>;
3698 close $fd;
3700 return wantarray ? @git_project_url_list : \@git_project_url_list;
3703 sub git_get_projects_list {
3704 my $filter = shift || '';
3705 my $paranoid = shift;
3706 my @list;
3708 if (-d $projects_list) {
3709 # search in directory
3710 my $dir = $projects_list;
3711 # remove the trailing "/"
3712 $dir =~ s!/+$!!;
3713 my $pfxlen = length("$dir");
3714 my $pfxdepth = ($dir =~ tr!/!!);
3715 # when filtering, search only given subdirectory
3716 if ($filter && !$paranoid) {
3717 $dir .= "/$filter";
3718 $dir =~ s!/+$!!;
3721 File::Find::find({
3722 follow_fast => 1, # follow symbolic links
3723 follow_skip => 2, # ignore duplicates
3724 dangling_symlinks => 0, # ignore dangling symlinks, silently
3725 wanted => sub {
3726 # global variables
3727 our $project_maxdepth;
3728 our $projectroot;
3729 # skip project-list toplevel, if we get it.
3730 return if (m!^[/.]$!);
3731 # only directories can be git repositories
3732 return unless (-d $_);
3733 # don't traverse too deep (Find is super slow on os x)
3734 # $project_maxdepth excludes depth of $projectroot
3735 if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
3736 $File::Find::prune = 1;
3737 return;
3740 my $path = substr($File::Find::name, $pfxlen + 1);
3741 # paranoidly only filter here
3742 if ($paranoid && $filter && $path !~ m!^\Q$filter\E/!) {
3743 next;
3745 # we check related file in $projectroot
3746 if (check_export_ok("$projectroot/$path")) {
3747 push @list, { path => $path };
3748 $File::Find::prune = 1;
3751 }, "$dir");
3753 } elsif (-f $projects_list) {
3754 # read from file(url-encoded):
3755 # 'git%2Fgit.git Linus+Torvalds'
3756 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3757 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3758 open my $fd, '<', $projects_list or return;
3759 PROJECT:
3760 while (my $line = <$fd>) {
3761 chomp $line;
3762 my ($path, $owner) = split ' ', $line;
3763 $path = unescape($path);
3764 $owner = unescape($owner);
3765 if (!defined $path) {
3766 next;
3768 # if $filter is rpovided, check if $path begins with $filter
3769 if ($filter && $path !~ m!^\Q$filter\E/!) {
3770 next;
3772 if (check_export_ok("$projectroot/$path")) {
3773 my $pr = {
3774 path => $path
3776 if ($owner) {
3777 $pr->{'owner'} = to_utf8($owner);
3779 push @list, $pr;
3782 close $fd;
3784 return @list;
3787 # written with help of Tree::Trie module (Perl Artistic License, GPL compatibile)
3788 # as side effects it sets 'forks' field to list of forks for forked projects
3789 sub filter_forks_from_projects_list {
3790 my $projects = shift;
3792 my %trie; # prefix tree of directories (path components)
3793 # generate trie out of those directories that might contain forks
3794 foreach my $pr (@$projects) {
3795 my $path = $pr->{'path'};
3796 $path =~ s/\.git$//; # forks of 'repo.git' are in 'repo/' directory
3797 next if ($path =~ m!/$!); # skip non-bare repositories, e.g. 'repo/.git'
3798 next unless ($path); # skip '.git' repository: tests, git-instaweb
3799 next unless (-d "$projectroot/$path"); # containing directory exists
3800 $pr->{'forks'} = []; # there can be 0 or more forks of project
3802 # add to trie
3803 my @dirs = split('/', $path);
3804 # walk the trie, until either runs out of components or out of trie
3805 my $ref = \%trie;
3806 while (scalar @dirs &&
3807 exists($ref->{$dirs[0]})) {
3808 $ref = $ref->{shift @dirs};
3810 # create rest of trie structure from rest of components
3811 foreach my $dir (@dirs) {
3812 $ref = $ref->{$dir} = {};
3814 # create end marker, store $pr as a data
3815 $ref->{''} = $pr if (!exists $ref->{''});
3818 # filter out forks, by finding shortest prefix match for paths
3819 my @filtered;
3820 PROJECT:
3821 foreach my $pr (@$projects) {
3822 # trie lookup
3823 my $ref = \%trie;
3824 DIR:
3825 foreach my $dir (split('/', $pr->{'path'})) {
3826 if (exists $ref->{''}) {
3827 # found [shortest] prefix, is a fork - skip it
3828 push @{$ref->{''}{'forks'}}, $pr;
3829 next PROJECT;
3831 if (!exists $ref->{$dir}) {
3832 # not in trie, cannot have prefix, not a fork
3833 push @filtered, $pr;
3834 next PROJECT;
3836 # If the dir is there, we just walk one step down the trie.
3837 $ref = $ref->{$dir};
3839 # we ran out of trie
3840 # (shouldn't happen: it's either no match, or end marker)
3841 push @filtered, $pr;
3844 return @filtered;
3847 # note: fill_project_list_info must be run first,
3848 # for 'descr_long' and 'ctags' to be filled
3849 sub search_projects_list {
3850 my ($projlist, %opts) = @_;
3851 my $tagfilter = $opts{'tagfilter'};
3852 my $search_re = $opts{'search_regexp'};
3854 return @$projlist
3855 unless ($tagfilter || $search_re);
3857 # searching projects require filling to be run before it;
3858 fill_project_list_info($projlist,
3859 $tagfilter ? 'ctags' : (),
3860 $search_re ? ('path', 'descr') : ());
3861 my @projects;
3862 PROJECT:
3863 foreach my $pr (@$projlist) {
3865 if ($tagfilter) {
3866 next unless ref($pr->{'ctags'}) eq 'HASH';
3867 next unless
3868 grep { lc($_) eq lc($tagfilter) } keys %{$pr->{'ctags'}};
3871 if ($search_re) {
3872 my $path = $pr->{'path'};
3873 $path =~ s/\.git$//; # should not be included in search
3874 next unless
3875 $path =~ /$search_re/ ||
3876 $pr->{'descr_long'} =~ /$search_re/;
3879 push @projects, $pr;
3882 return @projects;
3885 our $gitweb_project_owner = undef;
3886 sub git_get_project_list_from_file {
3888 return if (defined $gitweb_project_owner);
3890 $gitweb_project_owner = {};
3891 # read from file (url-encoded):
3892 # 'git%2Fgit.git Linus+Torvalds'
3893 # 'libs%2Fklibc%2Fklibc.git H.+Peter+Anvin'
3894 # 'linux%2Fhotplug%2Fudev.git Greg+Kroah-Hartman'
3895 if (-f $projects_list) {
3896 open(my $fd, '<', $projects_list);
3897 while (my $line = <$fd>) {
3898 chomp $line;
3899 my ($pr, $ow) = split ' ', $line;
3900 $pr = unescape($pr);
3901 $ow = unescape($ow);
3902 $gitweb_project_owner->{$pr} = to_utf8($ow);
3904 close $fd;
3908 sub git_get_project_owner {
3909 my $proj = shift;
3910 my $owner;
3912 return undef unless $proj;
3913 $git_dir = "$projectroot/$proj";
3915 if (defined $project && $proj eq $project) {
3916 $owner = git_get_project_config('owner');
3918 if (!defined $owner && !defined $gitweb_project_owner) {
3919 git_get_project_list_from_file();
3921 if (!defined $owner && exists $gitweb_project_owner->{$proj}) {
3922 $owner = $gitweb_project_owner->{$proj};
3924 if (!defined $owner && (!defined $project || $proj ne $project)) {
3925 $owner = git_get_project_config('owner');
3927 if (!defined $owner) {
3928 $owner = get_file_owner("$git_dir");
3931 return $owner;
3934 sub parse_activity_date {
3935 my $dstr = shift;
3937 if ($dstr =~ /^\s*([-+]?\d+)(?:\s+([-+]\d{4}))?\s*$/) {
3938 # Unix timestamp
3939 return 0 + $1;
3941 if ($dstr =~ /^\s*(\d{4})-(\d{2})-(\d{2})[Tt _](\d{1,2}):(\d{2}):(\d{2})(?:[ _]?([Zz]|(?:[-+]\d{1,2}:?\d{2})))?\s*$/) {
3942 my ($Y,$m,$d,$H,$M,$S,$z) = ($1,$2,$3,$4,$5,$6,$7||'');
3943 my $seconds = timegm(0+$S, 0+$M, 0+$H, 0+$d, $m-1, $Y-1900);
3944 defined($z) && $z ne '' or $z = 'Z';
3945 $z =~ s/://;
3946 substr($z,1,0) = '0' if length($z) == 4;
3947 my $off = 0;
3948 if (uc($z) ne 'Z') {
3949 $off = 60 * (60 * (0+substr($z,1,2)) + (0+substr($z,3,2)));
3950 $off = -$off if substr($z,0,1) eq '-';
3952 return $seconds - $off;
3954 return undef;
3957 # If $quick is true only look at $lastactivity_file
3958 sub git_get_last_activity {
3959 my ($path, $quick) = @_;
3960 my $fd;
3962 $git_dir = "$projectroot/$path";
3963 if ($lastactivity_file && open($fd, "<", "$git_dir/$lastactivity_file")) {
3964 my $activity = <$fd>;
3965 close $fd;
3966 return (undef) unless defined $activity;
3967 chomp $activity;
3968 return (undef) if $activity eq '';
3969 if (my $timestamp = parse_activity_date($activity)) {
3970 return ($timestamp);
3973 return (undef) if $quick;
3974 defined($fd = git_cmd_pipe 'for-each-ref',
3975 '--format=%(committer)',
3976 '--sort=-committerdate',
3977 '--count=1',
3978 map { "refs/$_" } get_branch_refs ()) or return;
3979 my $most_recent = <$fd>;
3980 close $fd or return (undef);
3981 if (defined $most_recent &&
3982 $most_recent =~ / (\d+) [-+][01]\d\d\d$/) {
3983 my $timestamp = $1;
3984 return ($timestamp);
3986 return (undef);
3989 # Implementation note: when a single remote is wanted, we cannot use 'git
3990 # remote show -n' because that command always work (assuming it's a remote URL
3991 # if it's not defined), and we cannot use 'git remote show' because that would
3992 # try to make a network roundtrip. So the only way to find if that particular
3993 # remote is defined is to walk the list provided by 'git remote -v' and stop if
3994 # and when we find what we want.
3995 sub git_get_remotes_list {
3996 my $wanted = shift;
3997 my %remotes = ();
3999 my $fd = git_cmd_pipe 'remote', '-v';
4000 return unless $fd;
4001 while (my $remote = to_utf8(scalar <$fd>)) {
4002 chomp $remote;
4003 $remote =~ s!\t(.*?)\s+\((\w+)\)$!!;
4004 next if $wanted and not $remote eq $wanted;
4005 my ($url, $key) = ($1, $2);
4007 $remotes{$remote} ||= { 'heads' => [] };
4008 $remotes{$remote}{$key} = $url;
4010 close $fd or return;
4011 return wantarray ? %remotes : \%remotes;
4014 # Takes a hash of remotes as first parameter and fills it by adding the
4015 # available remote heads for each of the indicated remotes.
4016 sub fill_remote_heads {
4017 my $remotes = shift;
4018 my @heads = map { "remotes/$_" } keys %$remotes;
4019 my @remoteheads = git_get_heads_list(undef, @heads);
4020 foreach my $remote (keys %$remotes) {
4021 $remotes->{$remote}{'heads'} = [ grep {
4022 $_->{'name'} =~ s!^$remote/!!
4023 } @remoteheads ];
4027 sub git_get_references {
4028 my $type = shift || "";
4029 my %refs;
4030 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
4031 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
4032 defined(my $fd = git_cmd_pipe "show-ref", "--dereference",
4033 ($type ? ("--", "refs/$type") : ())) # use -- <pattern> if $type
4034 or return;
4036 while (my $line = to_utf8(scalar <$fd>)) {
4037 chomp $line;
4038 if ($line =~ m!^([0-9a-fA-F]{40})\srefs/($type.*)$!) {
4039 if (defined $refs{$1}) {
4040 push @{$refs{$1}}, $2;
4041 } else {
4042 $refs{$1} = [ $2 ];
4046 close $fd or return;
4047 return \%refs;
4050 sub git_get_rev_name_tags {
4051 my $hash = shift || return undef;
4053 defined(my $fd = git_cmd_pipe "name-rev", "--tags", $hash)
4054 or return;
4055 my $name_rev = to_utf8(scalar <$fd>);
4056 close $fd;
4058 if ($name_rev =~ m|^$hash tags/(.*)$|) {
4059 return $1;
4060 } else {
4061 # catches also '$hash undefined' output
4062 return undef;
4066 ## ----------------------------------------------------------------------
4067 ## parse to hash functions
4069 sub parse_date {
4070 my $epoch = shift;
4071 my $tz = shift || "-0000";
4073 my %date;
4074 my @months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
4075 my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
4076 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($epoch);
4077 $date{'hour'} = $hour;
4078 $date{'minute'} = $min;
4079 $date{'mday'} = $mday;
4080 $date{'day'} = $days[$wday];
4081 $date{'month'} = $months[$mon];
4082 $date{'rfc2822'} = sprintf "%s, %d %s %4d %02d:%02d:%02d +0000",
4083 $days[$wday], $mday, $months[$mon], 1900+$year, $hour ,$min, $sec;
4084 $date{'mday-time'} = sprintf "%d %s %02d:%02d",
4085 $mday, $months[$mon], $hour ,$min;
4086 $date{'iso-8601'} = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
4087 1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
4089 my ($tz_sign, $tz_hour, $tz_min) =
4090 ($tz =~ m/^([-+])(\d\d)(\d\d)$/);
4091 $tz_sign = ($tz_sign eq '-' ? -1 : +1);
4092 my $local = $epoch + $tz_sign*((($tz_hour*60) + $tz_min)*60);
4093 ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = gmtime($local);
4094 $date{'hour_local'} = $hour;
4095 $date{'minute_local'} = $min;
4096 $date{'mday_local'} = $mday;
4097 $date{'tz_local'} = $tz;
4098 $date{'iso-tz'} = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
4099 1900+$year, $mon+1, $mday,
4100 $hour, $min, $sec, $tz);
4101 return %date;
4104 my %parse_date_rfc2822_month_names;
4105 BEGIN {
4106 %parse_date_rfc2822_month_names = (
4107 jan => 0, feb => 1, mar => 2, apr => 3, may => 4, jun => 5,
4108 jul => 6, aug => 7, sep => 8, oct => 9, nov => 10, dec => 11
4112 sub parse_date_rfc2822 {
4113 my $datestr = shift;
4114 return () unless defined $datestr;
4115 $datestr = $1 if $datestr =~/^[^\s]+,\s*(.*)$/;
4116 return () unless $datestr =~
4117 /^\s*(\d{1,2})\s+([A-Za-z]{3})\s+(\d{4})\s+(\d{1,2}):(\d{2}):(\d{2})\s+([+-]\d{4})\s*$/;
4118 my ($d,$b,$Y,$H,$M,$S,$z) = ($1,$2,$3,$4,$5,$6,$7);
4119 my $m = $parse_date_rfc2822_month_names{lc($b)};
4120 return () unless defined($m);
4121 my $seconds = timegm(0+$S, 0+$M, 0+$H, 0+$d, 0+$m, $Y-1900);
4122 my $tzoffset = 60 * (60 * (0+substr($z,1,2)) + (0+substr($z,3,2)));
4123 $tzoffset = -$tzoffset if substr($z,0,1) eq '-';
4124 my $tzstring;
4125 if ($tzoffset >= 0) {
4126 $tzstring = sprintf('+%02d%02d', int($tzoffset / 3600), int(($tzoffset % 3600) / 60));
4127 } else {
4128 $tzstring = sprintf('-%02d%02d', int(-$tzoffset / 3600), int((-$tzoffset % 3600) / 60));
4130 return parse_date($seconds - $tzoffset, $tzstring);
4133 sub parse_tag {
4134 my $tag_id = shift;
4135 my %tag;
4136 my @comment;
4138 defined(my $fd = git_cmd_pipe "cat-file", "tag", $tag_id) or return;
4139 $tag{'id'} = $tag_id;
4140 while (my $line = to_utf8(scalar <$fd>)) {
4141 chomp $line;
4142 if ($line =~ m/^object ([0-9a-fA-F]{40})$/) {
4143 $tag{'object'} = $1;
4144 } elsif ($line =~ m/^type (.+)$/) {
4145 $tag{'type'} = $1;
4146 } elsif ($line =~ m/^tag (.+)$/) {
4147 $tag{'name'} = $1;
4148 } elsif ($line =~ m/^tagger (.*) ([0-9]+) (.*)$/) {
4149 $tag{'author'} = $1;
4150 $tag{'author_epoch'} = $2;
4151 $tag{'author_tz'} = $3;
4152 if ($tag{'author'} =~ m/^([^<]+) <([^>]*)>/) {
4153 $tag{'author_name'} = $1;
4154 $tag{'author_email'} = $2;
4155 } else {
4156 $tag{'author_name'} = $tag{'author'};
4158 } elsif ($line =~ m/--BEGIN/) {
4159 push @comment, $line;
4160 last;
4161 } elsif ($line eq "") {
4162 last;
4165 push @comment, map(to_utf8($_), <$fd>);
4166 $tag{'comment'} = \@comment;
4167 close $fd or return;
4168 if (!defined $tag{'name'}) {
4169 return
4171 return %tag
4174 sub parse_commit_text {
4175 my ($commit_text, $withparents) = @_;
4176 my @commit_lines = split '\n', $commit_text;
4177 my %co;
4179 pop @commit_lines; # Remove '\0'
4181 if (! @commit_lines) {
4182 return;
4185 my $header = shift @commit_lines;
4186 if ($header !~ m/^[0-9a-fA-F]{40}/) {
4187 return;
4189 ($co{'id'}, my @parents) = split ' ', $header;
4190 while (my $line = shift @commit_lines) {
4191 last if $line eq "\n";
4192 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
4193 $co{'tree'} = $1;
4194 } elsif ((!defined $withparents) && ($line =~ m/^parent ([0-9a-fA-F]{40})$/)) {
4195 push @parents, $1;
4196 } elsif ($line =~ m/^author (.*) ([0-9]+) (.*)$/) {
4197 $co{'author'} = to_utf8($1);
4198 $co{'author_epoch'} = $2;
4199 $co{'author_tz'} = $3;
4200 if ($co{'author'} =~ m/^([^<]+) <([^>]*)>/) {
4201 $co{'author_name'} = $1;
4202 $co{'author_email'} = $2;
4203 } else {
4204 $co{'author_name'} = $co{'author'};
4206 } elsif ($line =~ m/^committer (.*) ([0-9]+) (.*)$/) {
4207 $co{'committer'} = to_utf8($1);
4208 $co{'committer_epoch'} = $2;
4209 $co{'committer_tz'} = $3;
4210 if ($co{'committer'} =~ m/^([^<]+) <([^>]*)>/) {
4211 $co{'committer_name'} = $1;
4212 $co{'committer_email'} = $2;
4213 } else {
4214 $co{'committer_name'} = $co{'committer'};
4218 if (!defined $co{'tree'}) {
4219 return;
4221 $co{'parents'} = \@parents;
4222 $co{'parent'} = $parents[0];
4224 @commit_lines = map to_utf8($_), @commit_lines;
4225 foreach my $title (@commit_lines) {
4226 $title =~ s/^ //;
4227 if ($title ne "") {
4228 $co{'title'} = chop_str($title, 80, 5);
4229 # remove leading stuff of merges to make the interesting part visible
4230 if (length($title) > 50) {
4231 $title =~ s/^Automatic //;
4232 $title =~ s/^merge (of|with) /Merge ... /i;
4233 if (length($title) > 50) {
4234 $title =~ s/(http|rsync):\/\///;
4236 if (length($title) > 50) {
4237 $title =~ s/(master|www|rsync)\.//;
4239 if (length($title) > 50) {
4240 $title =~ s/kernel.org:?//;
4242 if (length($title) > 50) {
4243 $title =~ s/\/pub\/scm//;
4246 $co{'title_short'} = chop_str($title, 50, 5);
4247 last;
4250 if (! defined $co{'title'} || $co{'title'} eq "") {
4251 $co{'title'} = $co{'title_short'} = '(no commit message)';
4253 # remove added spaces
4254 foreach my $line (@commit_lines) {
4255 $line =~ s/^ //;
4257 $co{'comment'} = \@commit_lines;
4259 my $age_epoch = $co{'committer_epoch'};
4260 $co{'age_epoch'} = $age_epoch;
4261 my $time_now = time;
4262 $co{'age_string'} = age_string($age_epoch, $time_now);
4263 $co{'age_string_date'} = age_string_date($age_epoch, $time_now);
4264 $co{'age_string_age'} = age_string_age($age_epoch, $time_now);
4265 return %co;
4268 sub parse_commit {
4269 my ($commit_id) = @_;
4270 my %co;
4272 local $/ = "\0";
4274 defined(my $fd = git_cmd_pipe "rev-list",
4275 "--parents",
4276 "--header",
4277 "--max-count=1",
4278 $commit_id,
4279 "--")
4280 or die_error(500, "Open git-rev-list failed");
4281 %co = parse_commit_text(<$fd>, 1);
4282 close $fd;
4284 return %co;
4287 sub parse_commits {
4288 my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
4289 my @cos;
4291 $maxcount ||= 1;
4292 $skip ||= 0;
4294 local $/ = "\0";
4296 defined(my $fd = git_cmd_pipe "rev-list",
4297 "--header",
4298 @args,
4299 ("--max-count=" . $maxcount),
4300 ("--skip=" . $skip),
4301 @extra_options,
4302 $commit_id,
4303 "--",
4304 ($filename ? ($filename) : ()))
4305 or die_error(500, "Open git-rev-list failed");
4306 while (my $line = <$fd>) {
4307 my %co = parse_commit_text($line);
4308 push @cos, \%co;
4310 close $fd;
4312 return wantarray ? @cos : \@cos;
4315 # parse line of git-diff-tree "raw" output
4316 sub parse_difftree_raw_line {
4317 my $line = shift;
4318 my %res;
4320 # ':100644 100644 03b218260e99b78c6df0ed378e59ed9205ccc96d 3b93d5e7cc7f7dd4ebed13a5cc1a4ad976fc94d8 M ls-files.c'
4321 # ':100644 100644 7f9281985086971d3877aca27704f2aaf9c448ce bc190ebc71bbd923f2b728e505408f5e54bd073a M rev-tree.c'
4322 if ($line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)([0-9]{0,3})\t(.*)$/) {
4323 $res{'from_mode'} = $1;
4324 $res{'to_mode'} = $2;
4325 $res{'from_id'} = $3;
4326 $res{'to_id'} = $4;
4327 $res{'status'} = $5;
4328 $res{'similarity'} = $6;
4329 if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
4330 ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
4331 } else {
4332 $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
4335 # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
4336 # combined diff (for merge commit)
4337 elsif ($line =~ s/^(::+)((?:[0-7]{6} )+)((?:[0-9a-fA-F]{40} )+)([a-zA-Z]+)\t(.*)$//) {
4338 $res{'nparents'} = length($1);
4339 $res{'from_mode'} = [ split(' ', $2) ];
4340 $res{'to_mode'} = pop @{$res{'from_mode'}};
4341 $res{'from_id'} = [ split(' ', $3) ];
4342 $res{'to_id'} = pop @{$res{'from_id'}};
4343 $res{'status'} = [ split('', $4) ];
4344 $res{'to_file'} = unquote($5);
4346 # 'c512b523472485aef4fff9e57b229d9d243c967f'
4347 elsif ($line =~ m/^([0-9a-fA-F]{40})$/) {
4348 $res{'commit'} = $1;
4351 return wantarray ? %res : \%res;
4354 # wrapper: return parsed line of git-diff-tree "raw" output
4355 # (the argument might be raw line, or parsed info)
4356 sub parsed_difftree_line {
4357 my $line_or_ref = shift;
4359 if (ref($line_or_ref) eq "HASH") {
4360 # pre-parsed (or generated by hand)
4361 return $line_or_ref;
4362 } else {
4363 return parse_difftree_raw_line($line_or_ref);
4367 # parse line of git-ls-tree output
4368 sub parse_ls_tree_line {
4369 my $line = shift;
4370 my %opts = @_;
4371 my %res;
4373 if ($opts{'-l'}) {
4374 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa 16717 panic.c'
4375 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40}) +(-|[0-9]+)\t(.+)$/s;
4377 $res{'mode'} = $1;
4378 $res{'type'} = $2;
4379 $res{'hash'} = $3;
4380 $res{'size'} = $4;
4381 if ($opts{'-z'}) {
4382 $res{'name'} = $5;
4383 } else {
4384 $res{'name'} = unquote($5);
4386 } else {
4387 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
4388 $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t(.+)$/s;
4390 $res{'mode'} = $1;
4391 $res{'type'} = $2;
4392 $res{'hash'} = $3;
4393 if ($opts{'-z'}) {
4394 $res{'name'} = $4;
4395 } else {
4396 $res{'name'} = unquote($4);
4400 return wantarray ? %res : \%res;
4403 # generates _two_ hashes, references to which are passed as 2 and 3 argument
4404 sub parse_from_to_diffinfo {
4405 my ($diffinfo, $from, $to, @parents) = @_;
4407 if ($diffinfo->{'nparents'}) {
4408 # combined diff
4409 $from->{'file'} = [];
4410 $from->{'href'} = [];
4411 fill_from_file_info($diffinfo, @parents)
4412 unless exists $diffinfo->{'from_file'};
4413 for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
4414 $from->{'file'}[$i] =
4415 defined $diffinfo->{'from_file'}[$i] ?
4416 $diffinfo->{'from_file'}[$i] :
4417 $diffinfo->{'to_file'};
4418 if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
4419 $from->{'href'}[$i] = href(action=>"blob",
4420 hash_base=>$parents[$i],
4421 hash=>$diffinfo->{'from_id'}[$i],
4422 file_name=>$from->{'file'}[$i]);
4423 } else {
4424 $from->{'href'}[$i] = undef;
4427 } else {
4428 # ordinary (not combined) diff
4429 $from->{'file'} = $diffinfo->{'from_file'};
4430 if ($diffinfo->{'status'} ne "A") { # not new (added) file
4431 $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
4432 hash=>$diffinfo->{'from_id'},
4433 file_name=>$from->{'file'});
4434 } else {
4435 delete $from->{'href'};
4439 $to->{'file'} = $diffinfo->{'to_file'};
4440 if (!is_deleted($diffinfo)) { # file exists in result
4441 $to->{'href'} = href(action=>"blob", hash_base=>$hash,
4442 hash=>$diffinfo->{'to_id'},
4443 file_name=>$to->{'file'});
4444 } else {
4445 delete $to->{'href'};
4449 ## ......................................................................
4450 ## parse to array of hashes functions
4452 sub git_get_heads_list {
4453 my ($limit, @classes) = @_;
4454 @classes = get_branch_refs() unless @classes;
4455 my @patterns = map { "refs/$_" } @classes;
4456 my @headslist;
4458 defined(my $fd = git_cmd_pipe 'for-each-ref',
4459 ($limit ? '--count='.($limit+1) : ()), '--sort=-committerdate',
4460 '--format=%(objectname) %(refname) %(subject)%00%(committer)',
4461 @patterns)
4462 or return;
4463 while (my $line = to_utf8(scalar <$fd>)) {
4464 my %ref_item;
4466 chomp $line;
4467 my ($refinfo, $committerinfo) = split(/\0/, $line);
4468 my ($hash, $name, $title) = split(' ', $refinfo, 3);
4469 my ($committer, $epoch, $tz) =
4470 ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
4471 $ref_item{'fullname'} = $name;
4472 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
4473 $name =~ s!^refs/($strip_refs|remotes)/!!;
4474 $ref_item{'name'} = $name;
4475 # for refs neither in 'heads' nor 'remotes' we want to
4476 # show their ref dir
4477 my $ref_dir = (defined $1) ? $1 : '';
4478 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
4479 $ref_item{'name'} .= ' (' . $ref_dir . ')';
4482 $ref_item{'id'} = $hash;
4483 $ref_item{'title'} = $title || '(no commit message)';
4484 $ref_item{'epoch'} = $epoch;
4485 if ($epoch) {
4486 $ref_item{'age'} = age_string($ref_item{'epoch'});
4487 } else {
4488 $ref_item{'age'} = "unknown";
4491 push @headslist, \%ref_item;
4493 close $fd;
4495 return wantarray ? @headslist : \@headslist;
4498 sub git_get_tags_list {
4499 my $limit = shift;
4500 my @tagslist;
4501 my $all = shift || 0;
4502 my $order = shift || $default_refs_order;
4503 my $sortkey = $all && $order eq 'name' ? 'refname' : '-creatordate';
4505 defined(my $fd = git_cmd_pipe 'for-each-ref',
4506 ($limit ? '--count='.($limit+1) : ()), "--sort=$sortkey",
4507 '--format=%(objectname) %(objecttype) %(refname) '.
4508 '%(*objectname) %(*objecttype) %(subject)%00%(creator)',
4509 ($all ? 'refs' : 'refs/tags'))
4510 or return;
4511 while (my $line = to_utf8(scalar <$fd>)) {
4512 my %ref_item;
4514 chomp $line;
4515 my ($refinfo, $creatorinfo) = split(/\0/, $line);
4516 my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
4517 my ($creator, $epoch, $tz) =
4518 ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
4519 $ref_item{'fullname'} = $name;
4520 $name =~ s!^refs/!! if $all;
4521 $name =~ s!^refs/tags/!! unless $all;
4523 $ref_item{'type'} = $type;
4524 $ref_item{'id'} = $id;
4525 $ref_item{'name'} = $name;
4526 if ($type eq "tag") {
4527 $ref_item{'subject'} = $title;
4528 $ref_item{'reftype'} = $reftype;
4529 $ref_item{'refid'} = $refid;
4530 } else {
4531 $ref_item{'reftype'} = $type;
4532 $ref_item{'refid'} = $id;
4535 if ($type eq "tag" || $type eq "commit") {
4536 $ref_item{'epoch'} = $epoch;
4537 if ($epoch) {
4538 $ref_item{'age'} = age_string($ref_item{'epoch'});
4539 } else {
4540 $ref_item{'age'} = "unknown";
4544 push @tagslist, \%ref_item;
4546 close $fd;
4548 return wantarray ? @tagslist : \@tagslist;
4551 ## ----------------------------------------------------------------------
4552 ## filesystem-related functions
4554 sub get_file_owner {
4555 my $path = shift;
4557 my ($dev, $ino, $mode, $nlink, $st_uid, $st_gid, $rdev, $size) = stat($path);
4558 my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid($st_uid);
4559 if (!defined $gcos) {
4560 return undef;
4562 my $owner = $gcos;
4563 $owner =~ s/[,;].*$//;
4564 return to_utf8($owner);
4567 # assume that file exists
4568 sub insert_file {
4569 my $filename = shift;
4571 open my $fd, '<', $filename;
4572 while (<$fd>) {
4573 print to_utf8($_);
4575 close $fd;
4578 ## ......................................................................
4579 ## mimetype related functions
4581 sub mimetype_guess_file {
4582 my $filename = shift;
4583 my $mimemap = shift;
4584 my $rawmode = shift;
4585 -r $mimemap or return undef;
4587 my %mimemap;
4588 open(my $mh, '<', $mimemap) or return undef;
4589 while (<$mh>) {
4590 next if m/^#/; # skip comments
4591 my ($mimetype, @exts) = split(/\s+/);
4592 foreach my $ext (@exts) {
4593 $mimemap{$ext} = $mimetype;
4596 close($mh);
4598 my ($ext, $ans);
4599 $ext = $1 if $filename =~ /\.([^.]*)$/;
4600 $ans = $mimemap{$ext} if $ext;
4601 if (defined $ans) {
4602 my $l = lc($ans);
4603 $ans = 'text/html' if $l eq 'application/xhtml+xml';
4604 if (!$rawmode) {
4605 $ans = 'text/xml' if $l =~ m!^application/[^\s:;,=]+\+xml$! ||
4606 $l eq 'image/svg+xml' ||
4607 $l eq 'application/xml-dtd' ||
4608 $l eq 'application/xml-external-parsed-entity';
4611 return $ans;
4614 sub mimetype_guess {
4615 my $filename = shift;
4616 my $rawmode = shift;
4617 my $mime;
4618 $filename =~ /\./ or return undef;
4620 if ($mimetypes_file) {
4621 my $file = $mimetypes_file;
4622 if ($file !~ m!^/!) { # if it is relative path
4623 # it is relative to project
4624 $file = "$projectroot/$project/$file";
4626 $mime = mimetype_guess_file($filename, $file, $rawmode);
4628 $mime ||= mimetype_guess_file($filename, '/etc/mime.types', $rawmode);
4629 return $mime;
4632 sub blob_mimetype {
4633 my $fd = shift;
4634 my $filename = shift;
4635 my $rawmode = shift;
4636 my $mime;
4638 # The -T/-B file operators produce the wrong result unless a perlio
4639 # layer is present when the file handle is a pipe that delivers less
4640 # than 512 bytes of data before reaching EOF.
4642 # If we are running in a Perl that uses the stdio layer rather than the
4643 # unix+perlio layers we will end up adding a perlio layer on top of the
4644 # stdio layer and get a second level of buffering. This is harmless
4645 # and it makes the -T/-B file operators work properly in all cases.
4647 binmode $fd, ":perlio" or die_error(500, "Adding perlio layer failed")
4648 unless grep /^perlio$/, PerlIO::get_layers($fd);
4650 $mime = mimetype_guess($filename, $rawmode) if defined $filename;
4652 if (!$mime && $filename) {
4653 if ($filename =~ m/\.html?$/i) {
4654 $mime = 'text/html';
4655 } elsif ($filename =~ m/\.xht(?:ml)?$/i) {
4656 $mime = 'text/html';
4657 } elsif ($filename =~ m/\.te?xt?$/i) {
4658 $mime = 'text/plain';
4659 } elsif ($filename =~ m/\.(?:markdown|md)$/i) {
4660 $mime = 'text/plain';
4661 } elsif ($filename =~ m/\.png$/i) {
4662 $mime = 'image/png';
4663 } elsif ($filename =~ m/\.gif$/i) {
4664 $mime = 'image/gif';
4665 } elsif ($filename =~ m/\.jpe?g$/i) {
4666 $mime = 'image/jpeg';
4667 } elsif ($filename =~ m/\.svgz?$/i) {
4668 $mime = 'image/svg+xml';
4672 # just in case
4673 return $default_blob_plain_mimetype || 'application/octet-stream' unless $fd || $mime;
4675 $mime = -T $fd ? 'text/plain' : 'application/octet-stream' unless $mime;
4677 return $mime;
4680 sub is_ascii {
4681 use bytes;
4682 my $data = shift;
4683 return scalar($data =~ /^[\x00-\x7f]*$/);
4686 sub is_valid_utf8 {
4687 my $data = shift;
4688 return utf8::decode($data);
4691 sub extract_html_charset {
4692 return undef unless $_[0] && "$_[0]</head>" =~ m#<head(?:\s+[^>]*)?(?<!/)>(.*?)</head\s*>#is;
4693 my $head = $1;
4694 return $2 if $head =~ m#<meta\s+charset\s*=\s*(['"])\s*([a-z0-9(:)_.+-]+)\s*\1\s*/?>#is;
4695 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) {
4696 my %kv = (lc($1) => $3, lc($4) => $6);
4697 my ($he, $c) = (lc($kv{'http-equiv'}), $kv{'content'});
4698 return $1 if $he && $c && $he eq 'content-type' &&
4699 $c =~ m!\s*text/html\s*;\s*charset\s*=\s*([a-z0-9(:)_.+-]+)\s*$!is;
4701 return undef;
4704 sub blob_contenttype {
4705 my ($fd, $file_name, $type) = @_;
4707 $type ||= blob_mimetype($fd, $file_name, 1);
4708 return $type unless $type =~ m!^text/.+!i;
4709 my ($leader, $charset, $htmlcharset);
4710 if ($fd && read($fd, $leader, 32768)) {{
4711 $charset='US-ASCII' if is_ascii($leader);
4712 return ("$type; charset=UTF-8", $leader) if !$charset && is_valid_utf8($leader);
4713 $charset='ISO-8859-1' unless $charset;
4714 $htmlcharset = extract_html_charset($leader) if $type eq 'text/html';
4715 if ($htmlcharset && $charset ne 'US-ASCII') {
4716 $htmlcharset = undef if $htmlcharset =~ /^(?:utf-8|us-ascii)$/i
4719 return ("$type; charset=$htmlcharset", $leader) if $htmlcharset;
4720 my $defcharset = $default_text_plain_charset || '';
4721 $defcharset =~ s/^\s+//;
4722 $defcharset =~ s/\s+$//;
4723 $defcharset = '' if $charset && $charset ne 'US-ASCII' && $defcharset =~ /^(?:utf-8|us-ascii)$/i;
4724 return ("$type; charset=" . ($defcharset || 'ISO-8859-1'), $leader);
4727 # peek the first upto 128 bytes off a file handle
4728 sub peek128bytes {
4729 my $fd = shift;
4731 use IO::Handle;
4732 use bytes;
4734 my $prefix128;
4735 return '' unless $fd && read($fd, $prefix128, 128);
4737 # In the general case, we're guaranteed only to be able to ungetc one
4738 # character (provided, of course, we actually got a character first).
4740 # However, we know:
4742 # 1) we are dealing with a :perlio layer since blob_mimetype will have
4743 # already been called at least once on the file handle before us
4745 # 2) we have an $fd positioned at the start of the input stream and
4746 # therefore know we were positioned at a buffer boundary before
4747 # reading the initial upto 128 bytes
4749 # 3) the buffer size is at least 512 bytes
4751 # 4) we are careful to only unget raw bytes
4753 # 5) we are attempting to unget exactly the same number of bytes we got
4755 # Given the above conditions we will ALWAYS be able to safely unget
4756 # the $prefix128 value we just got.
4758 # In fact, we could read up to 511 bytes and still be sure.
4759 # (Reading 512 might pop us into the next internal buffer, but probably
4760 # not since that could break the always able to unget at least the one
4761 # you just got guarantee.)
4763 map {$fd->ungetc(ord($_))} reverse(split //, $prefix128);
4765 return $prefix128;
4768 # guess file syntax for syntax highlighting; return undef if no highlighting
4769 # the name of syntax can (in the future) depend on syntax highlighter used
4770 sub guess_file_syntax {
4771 my ($fd, $mimetype, $file_name) = @_;
4772 return undef unless $fd && defined $file_name &&
4773 defined $mimetype && $mimetype =~ m!^text/.+!i;
4774 my $basename = basename($file_name, '.in');
4775 return $highlight_basename{$basename}
4776 if exists $highlight_basename{$basename};
4778 # Peek to see if there's a shebang or xml line.
4779 # We always operate on bytes when testing this.
4781 use bytes;
4782 my $shebang = peek128bytes($fd);
4783 if (length($shebang) >= 4 && $shebang =~ /^#!/) { # 4 would be '#!/x'
4784 foreach my $key (keys %highlight_shebang) {
4785 my $ar = ref($highlight_shebang{$key}) ?
4786 $highlight_shebang{$key} :
4787 [$highlight_shebang{key}];
4788 map {return $key if $shebang =~ /$_/} @$ar;
4791 return 'xml' if $shebang =~ m!^\s*<\?xml\s!; # "xml" must be lowercase
4794 $basename =~ /\.([^.]*)$/;
4795 my $ext = $1 or return undef;
4796 return $highlight_ext{$ext}
4797 if exists $highlight_ext{$ext};
4799 return undef;
4802 # run highlighter and return FD of its output,
4803 # or return original FD if no highlighting
4804 sub run_highlighter {
4805 my ($fd, $syntax) = @_;
4806 return $fd unless $fd && !eof($fd) && defined $highlight_bin && defined $syntax;
4808 defined(my $hifd = cmd_pipe $posix_shell_bin, '-c',
4809 quote_command(git_cmd(), "cat-file", "blob", $hash)." | ".
4810 quote_command($highlight_bin).
4811 " --replace-tabs=8 --fragment --syntax $syntax")
4812 or die_error(500, "Couldn't open file or run syntax highlighter");
4813 if (eof $hifd) {
4814 # just in case, should not happen as we tested !eof($fd) above
4815 return $fd if close($hifd);
4817 # should not happen
4818 !$! or die_error(500, "Couldn't close syntax highighter pipe");
4820 # leaving us with the only possibility a non-zero exit status (possibly a signal);
4821 # instead of dying horribly on this, just skip the highlighting
4822 # but do output a message about it to STDERR that will end up in the log
4823 print STDERR "warning: skipping failed highlight for --syntax $syntax: ".
4824 sprintf("child exit status 0x%x\n", $?);
4825 return $fd
4827 close $fd;
4828 return ($hifd, 1);
4831 ## ======================================================================
4832 ## functions printing HTML: header, footer, error page
4834 sub get_page_title {
4835 my $title = to_utf8($site_name);
4837 unless (defined $project) {
4838 if (defined $project_filter) {
4839 $title .= " - projects in '" . esc_path($project_filter) . "'";
4841 return $title;
4843 $title .= " - " . to_utf8($project);
4845 return $title unless (defined $action);
4846 my $action_print = $action eq 'blame_incremental' ? 'blame' : $action;
4847 $title .= "/$action_print"; # $action is US-ASCII (7bit ASCII)
4849 return $title unless (defined $file_name);
4850 $title .= " - " . esc_path($file_name);
4851 if ($action eq "tree" && $file_name !~ m|/$|) {
4852 $title .= "/";
4855 return $title;
4858 sub get_content_type_html {
4859 # We do not ever emit application/xhtml+xml since that gives us
4860 # no benefits and it makes many browsers (e.g. Firefox) exceedingly
4861 # strict, which is troublesome for example when showing user-supplied
4862 # README.html files.
4863 return 'text/html';
4866 sub print_feed_meta {
4867 if (defined $project) {
4868 my %href_params = get_feed_info();
4869 if (!exists $href_params{'-title'}) {
4870 $href_params{'-title'} = 'log';
4873 foreach my $format (qw(RSS Atom)) {
4874 my $type = lc($format);
4875 my %link_attr = (
4876 '-rel' => 'alternate',
4877 '-title' => esc_attr("$project - $href_params{'-title'} - $format feed"),
4878 '-type' => "application/$type+xml"
4881 $href_params{'extra_options'} = undef;
4882 $href_params{'action'} = $type;
4883 $link_attr{'-href'} = href(%href_params);
4884 print "<link ".
4885 "rel=\"$link_attr{'-rel'}\" ".
4886 "title=\"$link_attr{'-title'}\" ".
4887 "href=\"$link_attr{'-href'}\" ".
4888 "type=\"$link_attr{'-type'}\" ".
4889 "/>\n";
4891 $href_params{'extra_options'} = '--no-merges';
4892 $link_attr{'-href'} = href(%href_params);
4893 $link_attr{'-title'} .= ' (no merges)';
4894 print "<link ".
4895 "rel=\"$link_attr{'-rel'}\" ".
4896 "title=\"$link_attr{'-title'}\" ".
4897 "href=\"$link_attr{'-href'}\" ".
4898 "type=\"$link_attr{'-type'}\" ".
4899 "/>\n";
4902 } else {
4903 printf('<link rel="alternate" title="%s projects list" '.
4904 'href="%s" type="text/plain; charset=utf-8" />'."\n",
4905 esc_attr($site_name), href(project=>undef, action=>"project_index"));
4906 printf('<link rel="alternate" title="%s projects feeds" '.
4907 'href="%s" type="text/x-opml" />'."\n",
4908 esc_attr($site_name), href(project=>undef, action=>"opml"));
4912 sub print_header_links {
4913 my $status = shift;
4915 # print out each stylesheet that exist, providing backwards capability
4916 # for those people who defined $stylesheet in a config file
4917 if (defined $stylesheet) {
4918 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4919 } else {
4920 foreach my $stylesheet (@stylesheets) {
4921 next unless $stylesheet;
4922 print '<link rel="stylesheet" type="text/css" href="'.esc_url($stylesheet).'"/>'."\n";
4925 print_feed_meta()
4926 if ($status eq '200 OK');
4927 if (defined $favicon) {
4928 print qq(<link rel="shortcut icon" href=").esc_url($favicon).qq(" type="image/png" />\n);
4932 sub print_nav_breadcrumbs_path {
4933 my $dirprefix = undef;
4934 while (my $part = shift) {
4935 $dirprefix .= "/" if defined $dirprefix;
4936 $dirprefix .= $part;
4937 print $cgi->a({-href => href(project => undef,
4938 project_filter => $dirprefix,
4939 action => "project_list")},
4940 esc_html($part)) . " / ";
4944 sub print_nav_breadcrumbs {
4945 my %opts = @_;
4947 for my $crumb (@extra_breadcrumbs, [ $home_link_str => $home_link ]) {
4948 print $cgi->a({-href => esc_url($crumb->[1])}, $crumb->[0]) . " / ";
4950 if (defined $project) {
4951 my @dirname = split '/', $project;
4952 my $projectbasename = pop @dirname;
4953 print_nav_breadcrumbs_path(@dirname);
4954 print $cgi->a({-href => href(action=>"summary")}, esc_html($projectbasename));
4955 if (defined $action) {
4956 my $action_print = $action ;
4957 $action_print = 'blame' if $action_print eq 'blame_incremental';
4958 if (defined $opts{-action_extra}) {
4959 $action_print = $cgi->a({-href => href(action=>$action)},
4960 $action);
4962 print " / $action_print";
4964 if (defined $opts{-action_extra}) {
4965 print " / $opts{-action_extra}";
4967 print "\n";
4968 } elsif (defined $project_filter) {
4969 print_nav_breadcrumbs_path(split '/', $project_filter);
4973 sub print_search_form {
4974 if (!defined $searchtext) {
4975 $searchtext = "";
4977 my $search_hash;
4978 if (defined $hash_base) {
4979 $search_hash = $hash_base;
4980 } elsif (defined $hash) {
4981 $search_hash = $hash;
4982 } else {
4983 $search_hash = "HEAD";
4985 # We can't use href() here because we need to encode the
4986 # URL parameters into the form, not into the action link.
4987 my $action = $my_uri;
4988 my $use_pathinfo = gitweb_check_feature('pathinfo');
4989 if ($use_pathinfo) {
4990 # See notes about doubled / in href()
4991 $action =~ s,/$,,;
4992 $action .= "/".esc_path_info($project);
4994 print $cgi->start_form(-method => "get", -action => $action) .
4995 "<div class=\"search\">\n" .
4996 (!$use_pathinfo &&
4997 $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
4998 $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
4999 $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
5000 $cgi->popup_menu(-name => 'st', -default => 'commit',
5001 -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
5002 " " . $cgi->a({-href => href(action=>"search_help"),
5003 -title => "search help" }, "?") . " search:\n",
5004 $cgi->textfield(-name => "s", -value => $searchtext, -override => 1) . "\n" .
5005 "<span title=\"Extended regular expression\">" .
5006 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
5007 -checked => $search_use_regexp) .
5008 "</span>" .
5009 "</div>" .
5010 $cgi->end_form() . "\n";
5013 sub git_header_html {
5014 my $status = shift || "200 OK";
5015 my $expires = shift;
5016 my %opts = @_;
5018 my $title = get_page_title();
5019 my $content_type = get_content_type_html();
5020 print $cgi->header(-type=>$content_type, -charset => 'utf-8',
5021 -status=> $status, -expires => $expires)
5022 unless ($opts{'-no_http_header'});
5023 my $mod_perl_version = $ENV{'MOD_PERL'} ? " $ENV{'MOD_PERL'}" : '';
5024 print <<EOF;
5025 <?xml version="1.0" encoding="utf-8"?>
5026 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
5027 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
5028 <!-- git web interface version $version, (C) 2005-2006, Kay Sievers <kay.sievers\@vrfy.org>, Christian Gierke -->
5029 <!-- git core binaries version $git_version -->
5030 <head>
5031 <meta http-equiv="content-type" content="$content_type; charset=utf-8"/>
5032 <meta name="generator" content="gitweb/$version git/$git_version$mod_perl_version"/>
5033 <meta name="robots" content="index, nofollow"/>
5034 <title>$title</title>
5035 <script type="text/javascript">/* <![CDATA[ */
5036 function fixBlameLinks() {
5037 var allLinks = document.getElementsByTagName("a");
5038 for (var i = 0; i < allLinks.length; i++) {
5039 var link = allLinks.item(i);
5040 if (link.className == 'blamelink')
5041 link.href = link.href.replace("/blame/", "/blame_incremental/");
5044 /* ]]> */</script>
5046 # the stylesheet, favicon etc urls won't work correctly with path_info
5047 # unless we set the appropriate base URL
5048 if ($ENV{'PATH_INFO'}) {
5049 print "<base href=\"".esc_url($base_url)."\" />\n";
5051 print_header_links($status);
5053 if (defined $site_html_head_string) {
5054 print to_utf8($site_html_head_string);
5057 print "</head>\n" .
5058 "<body>\n";
5060 if (defined $site_header && -f $site_header) {
5061 insert_file($site_header);
5064 print "<div class=\"page_header\">\n";
5065 if (defined $logo) {
5066 print $cgi->a({-href => esc_url($logo_url),
5067 -title => $logo_label},
5068 $cgi->img({-src => esc_url($logo),
5069 -width => 72, -height => 27,
5070 -alt => "git",
5071 -class => "logo"}));
5073 print_nav_breadcrumbs(%opts);
5074 print "</div>\n";
5076 my $have_search = gitweb_check_feature('search');
5077 if (defined $project && $have_search) {
5078 print_search_form();
5082 sub compute_timed_interval {
5083 return "<?gitweb compute_timed_interval?>" if $cache_mode_active;
5084 return tv_interval($t0, [ gettimeofday() ]);
5087 sub compute_commands_count {
5088 return "<?gitweb compute_commands_count?>" if $cache_mode_active;
5089 my $s = $number_of_git_cmds == 1 ? '' : 's';
5090 return '<span id="generating_cmd">'.
5091 $number_of_git_cmds.
5092 "</span> git command$s";
5095 sub git_footer_html {
5096 my $feed_class = 'rss_logo';
5098 print "<div class=\"page_footer\">\n";
5099 if (defined $project) {
5100 my $descr = git_get_project_description($project);
5101 if (defined $descr) {
5102 print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
5105 my %href_params = get_feed_info();
5106 if (!%href_params) {
5107 $feed_class .= ' generic';
5109 $href_params{'-title'} ||= 'log';
5111 foreach my $format (qw(RSS Atom)) {
5112 $href_params{'action'} = lc($format);
5113 print $cgi->a({-href => href(%href_params),
5114 -title => "$href_params{'-title'} $format feed",
5115 -class => $feed_class}, $format)."\n";
5118 } else {
5119 print $cgi->a({-href => href(project=>undef, action=>"opml",
5120 project_filter => $project_filter),
5121 -class => $feed_class}, "OPML") . " ";
5122 print $cgi->a({-href => href(project=>undef, action=>"project_index",
5123 project_filter => $project_filter),
5124 -class => $feed_class}, "TXT") . "\n";
5126 print "</div>\n"; # class="page_footer"
5128 if (defined $t0 && gitweb_check_feature('timed')) {
5129 print "<div id=\"generating_info\">\n";
5130 print 'This page took '.
5131 '<span id="generating_time" class="time_span">'.
5132 compute_timed_interval().
5133 ' seconds </span>'.
5134 ' and '.
5135 compute_commands_count().
5136 " to generate.\n";
5137 print "</div>\n"; # class="page_footer"
5140 if (defined $site_footer && -f $site_footer) {
5141 insert_file($site_footer);
5144 print qq!<script type="text/javascript" src="!.esc_url($javascript).qq!"></script>\n!;
5145 if (defined $action &&
5146 $action eq 'blame_incremental') {
5147 print qq!<script type="text/javascript">\n!.
5148 qq!startBlame("!. href(action=>"blame_data", -replay=>1) .qq!",\n!.
5149 qq! "!. href() .qq!");\n!.
5150 qq!</script>\n!;
5151 } else {
5152 my ($jstimezone, $tz_cookie, $datetime_class) =
5153 gitweb_get_feature('javascript-timezone');
5155 print qq!<script type="text/javascript">\n!.
5156 qq!window.onload = function () {\n!;
5157 if (gitweb_check_feature('blame_incremental')) {
5158 print qq! fixBlameLinks();\n!;
5160 if (gitweb_check_feature('javascript-actions')) {
5161 print qq! fixLinks();\n!;
5163 if ($jstimezone && $tz_cookie && $datetime_class) {
5164 print qq! var tz_cookie = { name: '$tz_cookie', expires: 14, path: '/' };\n!. # in days
5165 qq! onloadTZSetup('$jstimezone', tz_cookie, '$datetime_class');\n!;
5167 print qq!};\n!.
5168 qq!</script>\n!;
5171 print "</body>\n" .
5172 "</html>";
5175 # die_error(<http_status_code>, <error_message>[, <detailed_html_description>])
5176 # Example: die_error(404, 'Hash not found')
5177 # By convention, use the following status codes (as defined in RFC 2616):
5178 # 400: Invalid or missing CGI parameters, or
5179 # requested object exists but has wrong type.
5180 # 403: Requested feature (like "pickaxe" or "snapshot") not enabled on
5181 # this server or project.
5182 # 404: Requested object/revision/project doesn't exist.
5183 # 500: The server isn't configured properly, or
5184 # an internal error occurred (e.g. failed assertions caused by bugs), or
5185 # an unknown error occurred (e.g. the git binary died unexpectedly).
5186 # 503: The server is currently unavailable (because it is overloaded,
5187 # or down for maintenance). Generally, this is a temporary state.
5188 sub die_error {
5189 my $status = shift || 500;
5190 my $error = esc_html(shift) || "Internal Server Error";
5191 my $extra = shift;
5192 my %opts = @_;
5194 my %http_responses = (
5195 400 => '400 Bad Request',
5196 403 => '403 Forbidden',
5197 404 => '404 Not Found',
5198 500 => '500 Internal Server Error',
5199 503 => '503 Service Unavailable',
5201 git_header_html($http_responses{$status}, undef, %opts);
5202 print <<EOF;
5203 <div class="page_body">
5204 <br /><br />
5205 $status - $error
5206 <br />
5208 if (defined $extra) {
5209 print "<hr />\n" .
5210 "$extra\n";
5212 print "</div>\n";
5214 git_footer_html();
5215 goto DONE_GITWEB
5216 unless ($opts{'-error_handler'});
5219 ## ----------------------------------------------------------------------
5220 ## functions printing or outputting HTML: navigation
5222 sub git_print_page_nav {
5223 my ($current, $suppress, $head, $treehead, $treebase, $extra) = @_;
5224 $extra = '' if !defined $extra; # pager or formats
5226 my @navs = qw(summary log commit commitdiff tree refs);
5227 if ($suppress) {
5228 @navs = grep { $_ ne $suppress } @navs;
5231 my %arg = map { $_ => {action=>$_} } @navs;
5232 if (defined $head) {
5233 for (qw(commit commitdiff)) {
5234 $arg{$_}{'hash'} = $head;
5236 if ($current =~ m/^(tree | log | shortlog | commit | commitdiff | search)$/x) {
5237 $arg{'log'}{'hash'} = $head;
5241 $arg{'log'}{'action'} = 'shortlog';
5242 if ($current eq 'log') {
5243 $current = 'shortlog';
5244 } elsif ($current eq 'shortlog') {
5245 $current = 'log';
5247 $arg{'tree'}{'hash'} = $treehead if defined $treehead;
5248 $arg{'tree'}{'hash_base'} = $treebase if defined $treebase;
5250 my @actions = gitweb_get_feature('actions');
5251 my $escname = $project;
5252 $escname =~ s/[+]/%2B/g;
5253 my %repl = (
5254 '%' => '%',
5255 'n' => $project, # project name
5256 'f' => $git_dir, # project path within filesystem
5257 'h' => $treehead || '', # current hash ('h' parameter)
5258 'b' => $treebase || '', # hash base ('hb' parameter)
5259 'e' => $escname, # project name with '+' escaped
5261 while (@actions) {
5262 my ($label, $link, $pos) = splice(@actions,0,3);
5263 # insert
5264 @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs;
5265 # munch munch
5266 $link =~ s/%([%nfhbe])/$repl{$1}/g;
5267 $arg{$label}{'_href'} = $link;
5270 print "<div class=\"page_nav\">\n" .
5271 (join " | ",
5272 map { $_ eq $current ?
5273 $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_")
5274 } @navs);
5275 print "<br/>\n$extra<br/>\n" .
5276 "</div>\n";
5279 # returns a submenu for the nagivation of the refs views (tags, heads,
5280 # remotes) with the current view disabled and the remotes view only
5281 # available if the feature is enabled
5282 sub format_ref_views {
5283 my ($current) = @_;
5284 my @ref_views = qw{tags heads};
5285 push @ref_views, 'remotes' if gitweb_check_feature('remote_heads');
5286 return join " | ", map {
5287 $_ eq $current ? $_ :
5288 $cgi->a({-href => href(action=>$_)}, $_)
5289 } @ref_views
5292 sub format_paging_nav {
5293 my ($action, $page, $has_next_link) = @_;
5294 my $paging_nav;
5297 if ($page > 0) {
5298 $paging_nav .=
5299 $cgi->a({-href => href(-replay=>1, page=>undef)}, "first") .
5300 " &#183; " .
5301 $cgi->a({-href => href(-replay=>1, page=>$page-1),
5302 -accesskey => "p", -title => "Alt-p"}, "prev");
5303 } else {
5304 $paging_nav .= "first &#183; prev";
5307 if ($has_next_link) {
5308 $paging_nav .= " &#183; " .
5309 $cgi->a({-href => href(-replay=>1, page=>$page+1),
5310 -accesskey => "n", -title => "Alt-n"}, "next");
5311 } else {
5312 $paging_nav .= " &#183; next";
5315 return $paging_nav;
5318 sub format_log_nav {
5319 my ($action, $page, $has_next_link) = @_;
5320 my $paging_nav;
5322 if ($action eq 'shortlog') {
5323 $paging_nav .= 'shortlog';
5324 } else {
5325 $paging_nav .= $cgi->a({-href => href(action=>'shortlog', -replay=>1)}, 'shortlog');
5327 $paging_nav .= ' | ';
5328 if ($action eq 'log') {
5329 $paging_nav .= 'fulllog';
5330 } else {
5331 $paging_nav .= $cgi->a({-href => href(action=>'log', -replay=>1)}, 'fulllog');
5334 $paging_nav .= " | " . format_paging_nav($action, $page, $has_next_link);
5335 return $paging_nav;
5338 ## ......................................................................
5339 ## functions printing or outputting HTML: div
5341 sub git_print_header_div {
5342 my ($action, $title, $hash, $hash_base, $extra) = @_;
5343 my %args = ();
5344 defined $extra or $extra = '';
5346 $args{'action'} = $action;
5347 $args{'hash'} = $hash if $hash;
5348 $args{'hash_base'} = $hash_base if $hash_base;
5350 my $link1 = $cgi->a({-href => href(%args), -class => "title"},
5351 $title ? $title : $action);
5352 my $link2 = $cgi->a({-href => href(%args), -class => "cover"}, "");
5353 print "<div class=\"header\">\n" . '<span class="title">' .
5354 $link1 . $extra . $link2 . '</span>' . "\n</div>\n";
5357 sub format_repo_url {
5358 my ($name, $url) = @_;
5359 return "<tr class=\"metadata_url\"><td>$name</td><td>$url</td></tr>\n";
5362 # Group output by placing it in a DIV element and adding a header.
5363 # Options for start_div() can be provided by passing a hash reference as the
5364 # first parameter to the function.
5365 # Options to git_print_header_div() can be provided by passing an array
5366 # reference. This must follow the options to start_div if they are present.
5367 # The content can be a scalar, which is output as-is, a scalar reference, which
5368 # is output after html escaping, an IO handle passed either as *handle or
5369 # *handle{IO}, or a function reference. In the latter case all following
5370 # parameters will be taken as argument to the content function call.
5371 sub git_print_section {
5372 my ($div_args, $header_args, $content);
5373 my $arg = shift;
5374 if (ref($arg) eq 'HASH') {
5375 $div_args = $arg;
5376 $arg = shift;
5378 if (ref($arg) eq 'ARRAY') {
5379 $header_args = $arg;
5380 $arg = shift;
5382 $content = $arg;
5384 print $cgi->start_div($div_args);
5385 git_print_header_div(@$header_args);
5387 if (ref($content) eq 'CODE') {
5388 $content->(@_);
5389 } elsif (ref($content) eq 'SCALAR') {
5390 print esc_html($$content);
5391 } elsif (ref($content) eq 'GLOB' or ref($content) eq 'IO::Handle') {
5392 while (<$content>) {
5393 print to_utf8($_);
5395 } elsif (!ref($content) && defined($content)) {
5396 print $content;
5399 print $cgi->end_div;
5402 sub format_timestamp_html {
5403 my $date = shift;
5404 my $strtime = $date->{'rfc2822'};
5406 my (undef, undef, $datetime_class) =
5407 gitweb_get_feature('javascript-timezone');
5408 if ($datetime_class) {
5409 $strtime = qq!<span class="$datetime_class">$strtime</span>!;
5412 my $localtime_format = '(%d %02d:%02d %s)';
5413 if ($date->{'hour_local'} < 6) {
5414 $localtime_format = '(%d <span class="atnight">%02d:%02d</span> %s)';
5416 $strtime .= ' ' .
5417 sprintf($localtime_format, $date->{'mday_local'},
5418 $date->{'hour_local'}, $date->{'minute_local'}, $date->{'tz_local'});
5420 return $strtime;
5423 # Outputs the author name and date in long form
5424 sub git_print_authorship {
5425 my $co = shift;
5426 my %opts = @_;
5427 my $tag = $opts{-tag} || 'div';
5428 my $author = $co->{'author_name'};
5430 my %ad = parse_date($co->{'author_epoch'}, $co->{'author_tz'});
5431 print "<$tag class=\"author_date\">" .
5432 format_search_author($author, "author", esc_html($author)) .
5433 " [".format_timestamp_html(\%ad)."]".
5434 git_get_avatar($co->{'author_email'}, -pad_before => 1) .
5435 "</$tag>\n";
5438 # Outputs table rows containing the full author or committer information,
5439 # in the format expected for 'commit' view (& similar).
5440 # Parameters are a commit hash reference, followed by the list of people
5441 # to output information for. If the list is empty it defaults to both
5442 # author and committer.
5443 sub git_print_authorship_rows {
5444 my $co = shift;
5445 # too bad we can't use @people = @_ || ('author', 'committer')
5446 my @people = @_;
5447 @people = ('author', 'committer') unless @people;
5448 foreach my $who (@people) {
5449 my %wd = parse_date($co->{"${who}_epoch"}, $co->{"${who}_tz"});
5450 print "<tr><td>$who</td><td>" .
5451 format_search_author($co->{"${who}_name"}, $who,
5452 esc_html($co->{"${who}_name"})) . " " .
5453 format_search_author($co->{"${who}_email"}, $who,
5454 esc_html("<" . $co->{"${who}_email"} . ">")) .
5455 "</td><td rowspan=\"2\">" .
5456 git_get_avatar($co->{"${who}_email"}, -size => 'double') .
5457 "</td></tr>\n" .
5458 "<tr>" .
5459 "<td></td><td>" .
5460 format_timestamp_html(\%wd) .
5461 "</td>" .
5462 "</tr>\n";
5466 sub git_print_page_path {
5467 my $name = shift;
5468 my $type = shift;
5469 my $hb = shift;
5472 print "<div class=\"page_path\">";
5473 print $cgi->a({-href => href(action=>"tree", hash_base=>$hb),
5474 -title => 'tree root'}, to_utf8("[$project]"));
5475 print " / ";
5476 if (defined $name) {
5477 my @dirname = split '/', $name;
5478 my $basename = pop @dirname;
5479 my $fullname = '';
5481 foreach my $dir (@dirname) {
5482 $fullname .= ($fullname ? '/' : '') . $dir;
5483 print $cgi->a({-href => href(action=>"tree", file_name=>$fullname,
5484 hash_base=>$hb),
5485 -title => $fullname}, esc_path($dir));
5486 print " / ";
5488 if (defined $type && $type eq 'blob') {
5489 print $cgi->a({-href => href(action=>"blob_plain", file_name=>$file_name,
5490 hash_base=>$hb),
5491 -title => $name}, esc_path($basename));
5492 } elsif (defined $type && $type eq 'tree') {
5493 print $cgi->a({-href => href(action=>"tree", file_name=>$file_name,
5494 hash_base=>$hb),
5495 -title => $name}, esc_path($basename));
5496 print " / ";
5497 } else {
5498 print esc_path($basename);
5501 print "<br/></div>\n";
5504 sub git_print_log {
5505 my $log = shift;
5506 my %opts = @_;
5508 if ($opts{'-remove_title'}) {
5509 # remove title, i.e. first line of log
5510 shift @$log;
5512 # remove leading empty lines
5513 while (defined $log->[0] && $log->[0] eq "") {
5514 shift @$log;
5517 # print log
5518 my $skip_blank_line = 0;
5519 foreach my $line (@$log) {
5520 if ($line =~ m/^\s*([A-Z][-A-Za-z]*-[Bb]y|C[Cc]): /) {
5521 if (! $opts{'-remove_signoff'}) {
5522 print "<span class=\"signoff\">" . esc_html($line) . "</span><br/>\n";
5523 $skip_blank_line = 1;
5525 next;
5528 if ($line =~ m,\s*([a-z]*link): (https?://\S+),i) {
5529 if (! $opts{'-remove_signoff'}) {
5530 print "<span class=\"signoff\">" . esc_html($1) . ": " .
5531 "<a href=\"" . esc_html($2) . "\">" . esc_html($2) . "</a>" .
5532 "</span><br/>\n";
5533 $skip_blank_line = 1;
5535 next;
5538 # print only one empty line
5539 # do not print empty line after signoff
5540 if ($line eq "") {
5541 next if ($skip_blank_line);
5542 $skip_blank_line = 1;
5543 } else {
5544 $skip_blank_line = 0;
5547 print format_log_line_html($line) . "<br/>\n";
5550 if ($opts{'-final_empty_line'}) {
5551 # end with single empty line
5552 print "<br/>\n" unless $skip_blank_line;
5556 # return link target (what link points to)
5557 sub git_get_link_target {
5558 my $hash = shift;
5559 my $link_target;
5561 # read link
5562 defined(my $fd = git_cmd_pipe "cat-file", "blob", $hash)
5563 or return;
5565 local $/ = undef;
5566 $link_target = to_utf8(scalar <$fd>);
5568 close $fd
5569 or return;
5571 return $link_target;
5574 # given link target, and the directory (basedir) the link is in,
5575 # return target of link relative to top directory (top tree);
5576 # return undef if it is not possible (including absolute links).
5577 sub normalize_link_target {
5578 my ($link_target, $basedir) = @_;
5580 # absolute symlinks (beginning with '/') cannot be normalized
5581 return if (substr($link_target, 0, 1) eq '/');
5583 # normalize link target to path from top (root) tree (dir)
5584 my $path;
5585 if ($basedir) {
5586 $path = $basedir . '/' . $link_target;
5587 } else {
5588 # we are in top (root) tree (dir)
5589 $path = $link_target;
5592 # remove //, /./, and /../
5593 my @path_parts;
5594 foreach my $part (split('/', $path)) {
5595 # discard '.' and ''
5596 next if (!$part || $part eq '.');
5597 # handle '..'
5598 if ($part eq '..') {
5599 if (@path_parts) {
5600 pop @path_parts;
5601 } else {
5602 # link leads outside repository (outside top dir)
5603 return;
5605 } else {
5606 push @path_parts, $part;
5609 $path = join('/', @path_parts);
5611 return $path;
5614 # print tree entry (row of git_tree), but without encompassing <tr> element
5615 sub git_print_tree_entry {
5616 my ($t, $basedir, $hash_base, $have_blame) = @_;
5618 my %base_key = ();
5619 $base_key{'hash_base'} = $hash_base if defined $hash_base;
5621 # The format of a table row is: mode list link. Where mode is
5622 # the mode of the entry, list is the name of the entry, an href,
5623 # and link is the action links of the entry.
5625 print "<td class=\"mode\">" . mode_str($t->{'mode'}) . "</td>\n";
5626 if (exists $t->{'size'}) {
5627 print "<td class=\"size\">$t->{'size'}</td>\n";
5629 if ($t->{'type'} eq "blob") {
5630 print "<td class=\"list\">" .
5631 $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
5632 file_name=>"$basedir$t->{'name'}", %base_key),
5633 -class => "list"}, esc_path($t->{'name'}));
5634 if (S_ISLNK(oct $t->{'mode'})) {
5635 my $link_target = git_get_link_target($t->{'hash'});
5636 if ($link_target) {
5637 my $norm_target = normalize_link_target($link_target, $basedir);
5638 if (defined $norm_target) {
5639 print " -> " .
5640 $cgi->a({-href => href(action=>"object", hash_base=>$hash_base,
5641 file_name=>$norm_target),
5642 -title => $norm_target}, esc_path($link_target));
5643 } else {
5644 print " -> " . esc_path($link_target);
5648 print "</td>\n";
5649 print "<td class=\"link\">";
5650 print $cgi->a({-href => href(action=>"blob", hash=>$t->{'hash'},
5651 file_name=>"$basedir$t->{'name'}", %base_key)},
5652 "blob");
5653 if ($have_blame) {
5654 print " | " .
5655 $cgi->a({-href => href(action=>"blame", hash=>$t->{'hash'},
5656 file_name=>"$basedir$t->{'name'}", %base_key),
5657 -class => "blamelink"},
5658 "blame");
5660 if (defined $hash_base) {
5661 print " | " .
5662 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
5663 hash=>$t->{'hash'}, file_name=>"$basedir$t->{'name'}")},
5664 "history");
5666 print " | " .
5667 $cgi->a({-href => href(action=>"blob_plain", hash_base=>$hash_base,
5668 file_name=>"$basedir$t->{'name'}")},
5669 "raw");
5670 print "</td>\n";
5672 } elsif ($t->{'type'} eq "tree") {
5673 print "<td class=\"list\">";
5674 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
5675 file_name=>"$basedir$t->{'name'}",
5676 %base_key)},
5677 esc_path($t->{'name'}));
5678 print "</td>\n";
5679 print "<td class=\"link\">";
5680 print $cgi->a({-href => href(action=>"tree", hash=>$t->{'hash'},
5681 file_name=>"$basedir$t->{'name'}",
5682 %base_key)},
5683 "tree");
5684 if (defined $hash_base) {
5685 print " | " .
5686 $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
5687 file_name=>"$basedir$t->{'name'}")},
5688 "history");
5690 print "</td>\n";
5691 } else {
5692 # unknown object: we can only present history for it
5693 # (this includes 'commit' object, i.e. submodule support)
5694 print "<td class=\"list\">" .
5695 esc_path($t->{'name'}) .
5696 "</td>\n";
5697 print "<td class=\"link\">";
5698 if (defined $hash_base) {
5699 print $cgi->a({-href => href(action=>"history",
5700 hash_base=>$hash_base,
5701 file_name=>"$basedir$t->{'name'}")},
5702 "history");
5704 print "</td>\n";
5708 ## ......................................................................
5709 ## functions printing large fragments of HTML
5711 # get pre-image filenames for merge (combined) diff
5712 sub fill_from_file_info {
5713 my ($diff, @parents) = @_;
5715 $diff->{'from_file'} = [ ];
5716 $diff->{'from_file'}[$diff->{'nparents'} - 1] = undef;
5717 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
5718 if ($diff->{'status'}[$i] eq 'R' ||
5719 $diff->{'status'}[$i] eq 'C') {
5720 $diff->{'from_file'}[$i] =
5721 git_get_path_by_hash($parents[$i], $diff->{'from_id'}[$i]);
5725 return $diff;
5728 # is current raw difftree line of file deletion
5729 sub is_deleted {
5730 my $diffinfo = shift;
5732 return $diffinfo->{'to_id'} eq ('0' x 40);
5735 # does patch correspond to [previous] difftree raw line
5736 # $diffinfo - hashref of parsed raw diff format
5737 # $patchinfo - hashref of parsed patch diff format
5738 # (the same keys as in $diffinfo)
5739 sub is_patch_split {
5740 my ($diffinfo, $patchinfo) = @_;
5742 return defined $diffinfo && defined $patchinfo
5743 && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
5747 sub git_difftree_body {
5748 my ($difftree, $hash, @parents) = @_;
5749 my ($parent) = $parents[0];
5750 my $have_blame = gitweb_check_feature('blame');
5751 print "<div class=\"list_head\">\n";
5752 if ($#{$difftree} > 10) {
5753 print(($#{$difftree} + 1) . " files changed:\n");
5755 print "</div>\n";
5757 print "<table class=\"" .
5758 (@parents > 1 ? "combined " : "") .
5759 "diff_tree\">\n";
5761 # header only for combined diff in 'commitdiff' view
5762 my $has_header = @$difftree && @parents > 1 && $action eq 'commitdiff';
5763 if ($has_header) {
5764 # table header
5765 print "<thead><tr>\n" .
5766 "<th></th><th></th>\n"; # filename, patchN link
5767 for (my $i = 0; $i < @parents; $i++) {
5768 my $par = $parents[$i];
5769 print "<th>" .
5770 $cgi->a({-href => href(action=>"commitdiff",
5771 hash=>$hash, hash_parent=>$par),
5772 -title => 'commitdiff to parent number ' .
5773 ($i+1) . ': ' . substr($par,0,7)},
5774 $i+1) .
5775 "&#160;</th>\n";
5777 print "</tr></thead>\n<tbody>\n";
5780 my $alternate = 1;
5781 my $patchno = 0;
5782 foreach my $line (@{$difftree}) {
5783 my $diff = parsed_difftree_line($line);
5785 if ($alternate) {
5786 print "<tr class=\"dark\">\n";
5787 } else {
5788 print "<tr class=\"light\">\n";
5790 $alternate ^= 1;
5792 if (exists $diff->{'nparents'}) { # combined diff
5794 fill_from_file_info($diff, @parents)
5795 unless exists $diff->{'from_file'};
5797 if (!is_deleted($diff)) {
5798 # file exists in the result (child) commit
5799 print "<td>" .
5800 $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5801 file_name=>$diff->{'to_file'},
5802 hash_base=>$hash),
5803 -class => "list"}, esc_path($diff->{'to_file'})) .
5804 "</td>\n";
5805 } else {
5806 print "<td>" .
5807 esc_path($diff->{'to_file'}) .
5808 "</td>\n";
5811 if ($action eq 'commitdiff') {
5812 # link to patch
5813 $patchno++;
5814 print "<td class=\"link\">" .
5815 $cgi->a({-href => href(-anchor=>"patch$patchno")},
5816 "patch") .
5817 " | " .
5818 "</td>\n";
5821 my $has_history = 0;
5822 my $not_deleted = 0;
5823 for (my $i = 0; $i < $diff->{'nparents'}; $i++) {
5824 my $hash_parent = $parents[$i];
5825 my $from_hash = $diff->{'from_id'}[$i];
5826 my $from_path = $diff->{'from_file'}[$i];
5827 my $status = $diff->{'status'}[$i];
5829 $has_history ||= ($status ne 'A');
5830 $not_deleted ||= ($status ne 'D');
5832 if ($status eq 'A') {
5833 print "<td class=\"link\" align=\"right\"> | </td>\n";
5834 } elsif ($status eq 'D') {
5835 print "<td class=\"link\">" .
5836 $cgi->a({-href => href(action=>"blob",
5837 hash_base=>$hash,
5838 hash=>$from_hash,
5839 file_name=>$from_path)},
5840 "blob" . ($i+1)) .
5841 " | </td>\n";
5842 } else {
5843 if ($diff->{'to_id'} eq $from_hash) {
5844 print "<td class=\"link nochange\">";
5845 } else {
5846 print "<td class=\"link\">";
5848 print $cgi->a({-href => href(action=>"blobdiff",
5849 hash=>$diff->{'to_id'},
5850 hash_parent=>$from_hash,
5851 hash_base=>$hash,
5852 hash_parent_base=>$hash_parent,
5853 file_name=>$diff->{'to_file'},
5854 file_parent=>$from_path)},
5855 "diff" . ($i+1)) .
5856 " | </td>\n";
5860 print "<td class=\"link\">";
5861 if ($not_deleted) {
5862 print $cgi->a({-href => href(action=>"blob",
5863 hash=>$diff->{'to_id'},
5864 file_name=>$diff->{'to_file'},
5865 hash_base=>$hash)},
5866 "blob");
5867 print " | " if ($has_history);
5869 if ($has_history) {
5870 print $cgi->a({-href => href(action=>"history",
5871 file_name=>$diff->{'to_file'},
5872 hash_base=>$hash)},
5873 "history");
5875 print "</td>\n";
5877 print "</tr>\n";
5878 next; # instead of 'else' clause, to avoid extra indent
5880 # else ordinary diff
5882 my ($to_mode_oct, $to_mode_str, $to_file_type);
5883 my ($from_mode_oct, $from_mode_str, $from_file_type);
5884 if ($diff->{'to_mode'} ne ('0' x 6)) {
5885 $to_mode_oct = oct $diff->{'to_mode'};
5886 if (S_ISREG($to_mode_oct)) { # only for regular file
5887 $to_mode_str = sprintf("%04o", $to_mode_oct & 0777); # permission bits
5889 $to_file_type = file_type($diff->{'to_mode'});
5891 if ($diff->{'from_mode'} ne ('0' x 6)) {
5892 $from_mode_oct = oct $diff->{'from_mode'};
5893 if (S_ISREG($from_mode_oct)) { # only for regular file
5894 $from_mode_str = sprintf("%04o", $from_mode_oct & 0777); # permission bits
5896 $from_file_type = file_type($diff->{'from_mode'});
5899 if ($diff->{'status'} eq "A") { # created
5900 my $mode_chng = "<span class=\"file_status new\">[new $to_file_type";
5901 $mode_chng .= " with mode: $to_mode_str" if $to_mode_str;
5902 $mode_chng .= "]</span>";
5903 print "<td>";
5904 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5905 hash_base=>$hash, file_name=>$diff->{'file'}),
5906 -class => "list"}, esc_path($diff->{'file'}));
5907 print "</td>\n";
5908 print "<td>$mode_chng</td>\n";
5909 print "<td class=\"link\">";
5910 if ($action eq 'commitdiff') {
5911 # link to patch
5912 $patchno++;
5913 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5914 "patch") .
5915 " | ";
5917 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5918 hash_base=>$hash, file_name=>$diff->{'file'})},
5919 "blob");
5920 print "</td>\n";
5922 } elsif ($diff->{'status'} eq "D") { # deleted
5923 my $mode_chng = "<span class=\"file_status deleted\">[deleted $from_file_type]</span>";
5924 print "<td>";
5925 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5926 hash_base=>$parent, file_name=>$diff->{'file'}),
5927 -class => "list"}, esc_path($diff->{'file'}));
5928 print "</td>\n";
5929 print "<td>$mode_chng</td>\n";
5930 print "<td class=\"link\">";
5931 if ($action eq 'commitdiff') {
5932 # link to patch
5933 $patchno++;
5934 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5935 "patch") .
5936 " | ";
5938 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'from_id'},
5939 hash_base=>$parent, file_name=>$diff->{'file'})},
5940 "blob") . " | ";
5941 if ($have_blame) {
5942 print $cgi->a({-href => href(action=>"blame", hash_base=>$parent,
5943 file_name=>$diff->{'file'}),
5944 -class => "blamelink"},
5945 "blame") . " | ";
5947 print $cgi->a({-href => href(action=>"history", hash_base=>$parent,
5948 file_name=>$diff->{'file'})},
5949 "history");
5950 print "</td>\n";
5952 } elsif ($diff->{'status'} eq "M" || $diff->{'status'} eq "T") { # modified, or type changed
5953 my $mode_chnge = "";
5954 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
5955 $mode_chnge = "<span class=\"file_status mode_chnge\">[changed";
5956 if ($from_file_type ne $to_file_type) {
5957 $mode_chnge .= " from $from_file_type to $to_file_type";
5959 if (($from_mode_oct & 0777) != ($to_mode_oct & 0777)) {
5960 if ($from_mode_str && $to_mode_str) {
5961 $mode_chnge .= " mode: $from_mode_str->$to_mode_str";
5962 } elsif ($to_mode_str) {
5963 $mode_chnge .= " mode: $to_mode_str";
5966 $mode_chnge .= "]</span>\n";
5968 print "<td>";
5969 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5970 hash_base=>$hash, file_name=>$diff->{'file'}),
5971 -class => "list"}, esc_path($diff->{'file'}));
5972 print "</td>\n";
5973 print "<td>$mode_chnge</td>\n";
5974 print "<td class=\"link\">";
5975 if ($action eq 'commitdiff') {
5976 # link to patch
5977 $patchno++;
5978 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
5979 "patch") .
5980 " | ";
5981 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
5982 # "commit" view and modified file (not onlu mode changed)
5983 print $cgi->a({-href => href(action=>"blobdiff",
5984 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
5985 hash_base=>$hash, hash_parent_base=>$parent,
5986 file_name=>$diff->{'file'})},
5987 "diff") .
5988 " | ";
5990 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
5991 hash_base=>$hash, file_name=>$diff->{'file'})},
5992 "blob") . " | ";
5993 if ($have_blame) {
5994 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
5995 file_name=>$diff->{'file'}),
5996 -class => "blamelink"},
5997 "blame") . " | ";
5999 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
6000 file_name=>$diff->{'file'})},
6001 "history");
6002 print "</td>\n";
6004 } elsif ($diff->{'status'} eq "R" || $diff->{'status'} eq "C") { # renamed or copied
6005 my %status_name = ('R' => 'moved', 'C' => 'copied');
6006 my $nstatus = $status_name{$diff->{'status'}};
6007 my $mode_chng = "";
6008 if ($diff->{'from_mode'} != $diff->{'to_mode'}) {
6009 # mode also for directories, so we cannot use $to_mode_str
6010 $mode_chng = sprintf(", mode: %04o", $to_mode_oct & 0777);
6012 print "<td>" .
6013 $cgi->a({-href => href(action=>"blob", hash_base=>$hash,
6014 hash=>$diff->{'to_id'}, file_name=>$diff->{'to_file'}),
6015 -class => "list"}, esc_path($diff->{'to_file'})) . "</td>\n" .
6016 "<td><span class=\"file_status $nstatus\">[$nstatus from " .
6017 $cgi->a({-href => href(action=>"blob", hash_base=>$parent,
6018 hash=>$diff->{'from_id'}, file_name=>$diff->{'from_file'}),
6019 -class => "list"}, esc_path($diff->{'from_file'})) .
6020 " with " . (int $diff->{'similarity'}) . "% similarity$mode_chng]</span></td>\n" .
6021 "<td class=\"link\">";
6022 if ($action eq 'commitdiff') {
6023 # link to patch
6024 $patchno++;
6025 print $cgi->a({-href => href(-anchor=>"patch$patchno")},
6026 "patch") .
6027 " | ";
6028 } elsif ($diff->{'to_id'} ne $diff->{'from_id'}) {
6029 # "commit" view and modified file (not only pure rename or copy)
6030 print $cgi->a({-href => href(action=>"blobdiff",
6031 hash=>$diff->{'to_id'}, hash_parent=>$diff->{'from_id'},
6032 hash_base=>$hash, hash_parent_base=>$parent,
6033 file_name=>$diff->{'to_file'}, file_parent=>$diff->{'from_file'})},
6034 "diff") .
6035 " | ";
6037 print $cgi->a({-href => href(action=>"blob", hash=>$diff->{'to_id'},
6038 hash_base=>$parent, file_name=>$diff->{'to_file'})},
6039 "blob") . " | ";
6040 if ($have_blame) {
6041 print $cgi->a({-href => href(action=>"blame", hash_base=>$hash,
6042 file_name=>$diff->{'to_file'}),
6043 -class => "blamelink"},
6044 "blame") . " | ";
6046 print $cgi->a({-href => href(action=>"history", hash_base=>$hash,
6047 file_name=>$diff->{'to_file'})},
6048 "history");
6049 print "</td>\n";
6051 } # we should not encounter Unmerged (U) or Unknown (X) status
6052 print "</tr>\n";
6054 print "</tbody>" if $has_header;
6055 print "</table>\n";
6058 # Print context lines and then rem/add lines in a side-by-side manner.
6059 sub print_sidebyside_diff_lines {
6060 my ($ctx, $rem, $add) = @_;
6062 # print context block before add/rem block
6063 if (@$ctx) {
6064 print join '',
6065 '<div class="chunk_block ctx">',
6066 '<div class="old">',
6067 @$ctx,
6068 '</div>',
6069 '<div class="new">',
6070 @$ctx,
6071 '</div>',
6072 '</div>';
6075 if (!@$add) {
6076 # pure removal
6077 print join '',
6078 '<div class="chunk_block rem">',
6079 '<div class="old">',
6080 @$rem,
6081 '</div>',
6082 '</div>';
6083 } elsif (!@$rem) {
6084 # pure addition
6085 print join '',
6086 '<div class="chunk_block add">',
6087 '<div class="new">',
6088 @$add,
6089 '</div>',
6090 '</div>';
6091 } else {
6092 print join '',
6093 '<div class="chunk_block chg">',
6094 '<div class="old">',
6095 @$rem,
6096 '</div>',
6097 '<div class="new">',
6098 @$add,
6099 '</div>',
6100 '</div>';
6104 # Print context lines and then rem/add lines in inline manner.
6105 sub print_inline_diff_lines {
6106 my ($ctx, $rem, $add) = @_;
6108 print @$ctx, @$rem, @$add;
6111 # Format removed and added line, mark changed part and HTML-format them.
6112 # Implementation is based on contrib/diff-highlight
6113 sub format_rem_add_lines_pair {
6114 my ($rem, $add, $num_parents) = @_;
6116 # We need to untabify lines before split()'ing them;
6117 # otherwise offsets would be invalid.
6118 chomp $rem;
6119 chomp $add;
6120 $rem = untabify($rem);
6121 $add = untabify($add);
6123 my @rem = split(//, $rem);
6124 my @add = split(//, $add);
6125 my ($esc_rem, $esc_add);
6126 # Ignore leading +/- characters for each parent.
6127 my ($prefix_len, $suffix_len) = ($num_parents, 0);
6128 my ($prefix_has_nonspace, $suffix_has_nonspace);
6130 my $shorter = (@rem < @add) ? @rem : @add;
6131 while ($prefix_len < $shorter) {
6132 last if ($rem[$prefix_len] ne $add[$prefix_len]);
6134 $prefix_has_nonspace = 1 if ($rem[$prefix_len] !~ /\s/);
6135 $prefix_len++;
6138 while ($prefix_len + $suffix_len < $shorter) {
6139 last if ($rem[-1 - $suffix_len] ne $add[-1 - $suffix_len]);
6141 $suffix_has_nonspace = 1 if ($rem[-1 - $suffix_len] !~ /\s/);
6142 $suffix_len++;
6145 # Mark lines that are different from each other, but have some common
6146 # part that isn't whitespace. If lines are completely different, don't
6147 # mark them because that would make output unreadable, especially if
6148 # diff consists of multiple lines.
6149 if ($prefix_has_nonspace || $suffix_has_nonspace) {
6150 $esc_rem = esc_html_hl_regions($rem, 'marked',
6151 [$prefix_len, @rem - $suffix_len], -nbsp=>1);
6152 $esc_add = esc_html_hl_regions($add, 'marked',
6153 [$prefix_len, @add - $suffix_len], -nbsp=>1);
6154 } else {
6155 $esc_rem = esc_html($rem, -nbsp=>1);
6156 $esc_add = esc_html($add, -nbsp=>1);
6159 return format_diff_line(\$esc_rem, 'rem'),
6160 format_diff_line(\$esc_add, 'add');
6163 # HTML-format diff context, removed and added lines.
6164 sub format_ctx_rem_add_lines {
6165 my ($ctx, $rem, $add, $num_parents) = @_;
6166 my (@new_ctx, @new_rem, @new_add);
6167 my $can_highlight = 0;
6168 my $is_combined = ($num_parents > 1);
6170 # Highlight if every removed line has a corresponding added line.
6171 if (@$add > 0 && @$add == @$rem) {
6172 $can_highlight = 1;
6174 # Highlight lines in combined diff only if the chunk contains
6175 # diff between the same version, e.g.
6177 # - a
6178 # - b
6179 # + c
6180 # + d
6182 # Otherwise the highlightling would be confusing.
6183 if ($is_combined) {
6184 for (my $i = 0; $i < @$add; $i++) {
6185 my $prefix_rem = substr($rem->[$i], 0, $num_parents);
6186 my $prefix_add = substr($add->[$i], 0, $num_parents);
6188 $prefix_rem =~ s/-/+/g;
6190 if ($prefix_rem ne $prefix_add) {
6191 $can_highlight = 0;
6192 last;
6198 if ($can_highlight) {
6199 for (my $i = 0; $i < @$add; $i++) {
6200 my ($line_rem, $line_add) = format_rem_add_lines_pair(
6201 $rem->[$i], $add->[$i], $num_parents);
6202 push @new_rem, $line_rem;
6203 push @new_add, $line_add;
6205 } else {
6206 @new_rem = map { format_diff_line($_, 'rem') } @$rem;
6207 @new_add = map { format_diff_line($_, 'add') } @$add;
6210 @new_ctx = map { format_diff_line($_, 'ctx') } @$ctx;
6212 return (\@new_ctx, \@new_rem, \@new_add);
6215 # Print context lines and then rem/add lines.
6216 sub print_diff_lines {
6217 my ($ctx, $rem, $add, $diff_style, $num_parents) = @_;
6218 my $is_combined = $num_parents > 1;
6220 ($ctx, $rem, $add) = format_ctx_rem_add_lines($ctx, $rem, $add,
6221 $num_parents);
6223 if ($diff_style eq 'sidebyside' && !$is_combined) {
6224 print_sidebyside_diff_lines($ctx, $rem, $add);
6225 } else {
6226 # default 'inline' style and unknown styles
6227 print_inline_diff_lines($ctx, $rem, $add);
6231 sub print_diff_chunk {
6232 my ($diff_style, $num_parents, $from, $to, @chunk) = @_;
6233 my (@ctx, @rem, @add);
6235 # The class of the previous line.
6236 my $prev_class = '';
6238 return unless @chunk;
6240 # incomplete last line might be among removed or added lines,
6241 # or both, or among context lines: find which
6242 for (my $i = 1; $i < @chunk; $i++) {
6243 if ($chunk[$i][0] eq 'incomplete') {
6244 $chunk[$i][0] = $chunk[$i-1][0];
6248 # guardian
6249 push @chunk, ["", ""];
6251 foreach my $line_info (@chunk) {
6252 my ($class, $line) = @$line_info;
6254 # print chunk headers
6255 if ($class && $class eq 'chunk_header') {
6256 print format_diff_line($line, $class, $from, $to);
6257 next;
6260 ## print from accumulator when have some add/rem lines or end
6261 # of chunk (flush context lines), or when have add and rem
6262 # lines and new block is reached (otherwise add/rem lines could
6263 # be reordered)
6264 if (!$class || ((@rem || @add) && $class eq 'ctx') ||
6265 (@rem && @add && $class ne $prev_class)) {
6266 print_diff_lines(\@ctx, \@rem, \@add,
6267 $diff_style, $num_parents);
6268 @ctx = @rem = @add = ();
6271 ## adding lines to accumulator
6272 # guardian value
6273 last unless $line;
6274 # rem, add or change
6275 if ($class eq 'rem') {
6276 push @rem, $line;
6277 } elsif ($class eq 'add') {
6278 push @add, $line;
6280 # context line
6281 if ($class eq 'ctx') {
6282 push @ctx, $line;
6285 $prev_class = $class;
6289 sub git_patchset_body {
6290 my ($fd, $diff_style, $difftree, $hash, @hash_parents) = @_;
6291 my ($hash_parent) = $hash_parents[0];
6293 my $is_combined = (@hash_parents > 1);
6294 my $patch_idx = 0;
6295 my $patch_number = 0;
6296 my $patch_line;
6297 my $diffinfo;
6298 my $to_name;
6299 my (%from, %to);
6300 my @chunk; # for side-by-side diff
6302 print "<div class=\"patchset\">\n";
6304 # skip to first patch
6305 while ($patch_line = to_utf8(scalar <$fd>)) {
6306 chomp $patch_line;
6308 last if ($patch_line =~ m/^diff /);
6311 PATCH:
6312 while ($patch_line) {
6314 # parse "git diff" header line
6315 if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
6316 # $1 is from_name, which we do not use
6317 $to_name = unquote($2);
6318 $to_name =~ s!^b/!!;
6319 } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
6320 # $1 is 'cc' or 'combined', which we do not use
6321 $to_name = unquote($2);
6322 } else {
6323 $to_name = undef;
6326 # check if current patch belong to current raw line
6327 # and parse raw git-diff line if needed
6328 if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
6329 # this is continuation of a split patch
6330 print "<div class=\"patch cont\">\n";
6331 } else {
6332 # advance raw git-diff output if needed
6333 $patch_idx++ if defined $diffinfo;
6335 # read and prepare patch information
6336 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
6338 # compact combined diff output can have some patches skipped
6339 # find which patch (using pathname of result) we are at now;
6340 if ($is_combined) {
6341 while ($to_name ne $diffinfo->{'to_file'}) {
6342 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
6343 format_diff_cc_simplified($diffinfo, @hash_parents) .
6344 "</div>\n"; # class="patch"
6346 $patch_idx++;
6347 $patch_number++;
6349 last if $patch_idx > $#$difftree;
6350 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
6354 # modifies %from, %to hashes
6355 parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
6357 # this is first patch for raw difftree line with $patch_idx index
6358 # we index @$difftree array from 0, but number patches from 1
6359 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
6362 # git diff header
6363 #assert($patch_line =~ m/^diff /) if DEBUG;
6364 #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
6365 $patch_number++;
6366 # print "git diff" header
6367 print format_git_diff_header_line($patch_line, $diffinfo,
6368 \%from, \%to);
6370 # print extended diff header
6371 print "<div class=\"diff extended_header\">\n";
6372 EXTENDED_HEADER:
6373 while ($patch_line = to_utf8(scalar<$fd>)) {
6374 chomp $patch_line;
6376 last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
6378 print format_extended_diff_header_line($patch_line, $diffinfo,
6379 \%from, \%to);
6381 print "</div>\n"; # class="diff extended_header"
6383 # from-file/to-file diff header
6384 if (! $patch_line) {
6385 print "</div>\n"; # class="patch"
6386 last PATCH;
6388 next PATCH if ($patch_line =~ m/^diff /);
6389 #assert($patch_line =~ m/^---/) if DEBUG;
6391 my $last_patch_line = $patch_line;
6392 $patch_line = to_utf8(scalar <$fd>);
6393 chomp $patch_line;
6394 #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
6396 print format_diff_from_to_header($last_patch_line, $patch_line,
6397 $diffinfo, \%from, \%to,
6398 @hash_parents);
6400 # the patch itself
6401 LINE:
6402 while ($patch_line = to_utf8(scalar <$fd>)) {
6403 chomp $patch_line;
6405 next PATCH if ($patch_line =~ m/^diff /);
6407 my $class = diff_line_class($patch_line, \%from, \%to);
6409 if ($class eq 'chunk_header') {
6410 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
6411 @chunk = ();
6414 push @chunk, [ $class, $patch_line ];
6417 } continue {
6418 if (@chunk) {
6419 print_diff_chunk($diff_style, scalar @hash_parents, \%from, \%to, @chunk);
6420 @chunk = ();
6422 print "</div>\n"; # class="patch"
6425 # for compact combined (--cc) format, with chunk and patch simplification
6426 # the patchset might be empty, but there might be unprocessed raw lines
6427 for (++$patch_idx if $patch_number > 0;
6428 $patch_idx < @$difftree;
6429 ++$patch_idx) {
6430 # read and prepare patch information
6431 $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
6433 # generate anchor for "patch" links in difftree / whatchanged part
6434 print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
6435 format_diff_cc_simplified($diffinfo, @hash_parents) .
6436 "</div>\n"; # class="patch"
6438 $patch_number++;
6441 if ($patch_number == 0) {
6442 if (@hash_parents > 1) {
6443 print "<div class=\"diff nodifferences\">Trivial merge</div>\n";
6444 } else {
6445 print "<div class=\"diff nodifferences\">No differences found</div>\n";
6449 print "</div>\n"; # class="patchset"
6452 # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6454 sub git_project_search_form {
6455 my ($searchtext, $search_use_regexp) = @_;
6457 my $limit = '';
6458 if ($project_filter) {
6459 $limit = " in '$project_filter'";
6462 print "<div class=\"projsearch\">\n";
6463 print $cgi->start_form(-method => 'get', -action => $my_uri) .
6464 $cgi->hidden(-name => 'a', -value => 'project_list') . "\n";
6465 print $cgi->hidden(-name => 'pf', -value => $project_filter). "\n"
6466 if (defined $project_filter);
6467 print $cgi->textfield(-name => 's', -value => $searchtext,
6468 -title => "Search project by name and description$limit",
6469 -size => 60) . "\n" .
6470 "<span title=\"Extended regular expression\">" .
6471 $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
6472 -checked => $search_use_regexp) .
6473 "</span>\n" .
6474 $cgi->submit(-name => 'btnS', -value => 'Search') .
6475 $cgi->end_form() . "\n" .
6476 "<span class=\"projectlist_link\">" .
6477 $cgi->a({-href => href(project => undef, searchtext => undef,
6478 action => 'project_list',
6479 project_filter => $project_filter)},
6480 esc_html("List all projects$limit")) . "</span><br />\n";
6481 print "<span class=\"projectlist_link\">" .
6482 $cgi->a({-href => href(project => undef, searchtext => undef,
6483 action => 'project_list',
6484 project_filter => undef)},
6485 esc_html("List all projects")) . "</span>\n" if $project_filter;
6486 print "</div>\n";
6489 # entry for given @keys needs filling if at least one of keys in list
6490 # is not present in %$project_info
6491 sub project_info_needs_filling {
6492 my ($project_info, @keys) = @_;
6494 # return List::MoreUtils::any { !exists $project_info->{$_} } @keys;
6495 foreach my $key (@keys) {
6496 if (!exists $project_info->{$key}) {
6497 return 1;
6500 return;
6503 sub git_cache_file_format {
6504 return GITWEB_CACHE_FORMAT .
6505 (gitweb_check_feature('forks') ? " (forks)" : "");
6508 sub git_retrieve_cache_file {
6509 my $cache_file = shift;
6511 use Storable qw(retrieve);
6513 if ((my $dump = eval { retrieve($cache_file) })) {
6514 return $$dump[1] if
6515 ref($dump) eq 'ARRAY' &&
6516 @$dump == 2 &&
6517 ref($$dump[1]) eq 'ARRAY' &&
6518 @{$$dump[1]} == 2 &&
6519 ref(${$$dump[1]}[0]) eq 'ARRAY' &&
6520 ref(${$$dump[1]}[1]) eq 'HASH' &&
6521 $$dump[0] eq git_cache_file_format();
6524 return undef;
6527 sub git_store_cache_file {
6528 my ($cache_file, $cachedata) = @_;
6530 use File::Basename qw(dirname);
6531 use File::stat;
6532 use POSIX qw(:fcntl_h);
6533 use Storable qw(store_fd);
6535 my $result = undef;
6536 my $cache_d = dirname($cache_file);
6537 my $mask = umask();
6538 umask($mask & ~0070) if $cache_grpshared;
6539 if ((-d $cache_d || mkdir($cache_d, $cache_grpshared ? 0770 : 0700)) &&
6540 sysopen(my $fd, "$cache_file.lock", O_WRONLY|O_CREAT|O_EXCL, $cache_grpshared ? 0660 : 0600)) {
6541 store_fd([git_cache_file_format(), $cachedata], $fd);
6542 close $fd;
6543 rename "$cache_file.lock", $cache_file;
6544 $result = stat($cache_file)->mtime;
6546 umask($mask) if $cache_grpshared;
6547 return $result;
6550 sub verify_cached_project {
6551 my ($hashref, $path) = @_;
6552 return undef unless $path;
6553 delete $$hashref{$path}, return undef unless is_valid_project($path);
6554 return $$hashref{$path} if exists $$hashref{$path};
6556 # A valid project was requested but it's not yet in the cache
6557 # Manufacture a minimal project entry (path, name, description)
6558 # Also provide age, but only if it's available via $lastactivity_file
6560 my %proj = ('path' => $path);
6561 my $val = git_get_project_description($path);
6562 defined $val or $val = '';
6563 $proj{'descr_long'} = $val;
6564 $proj{'descr'} = chop_str($val, $projects_list_description_width, 5);
6565 unless ($omit_owner) {
6566 $val = git_get_project_owner($path);
6567 defined $val or $val = '';
6568 $proj{'owner'} = $val;
6570 unless ($omit_age_column) {
6571 ($val) = git_get_last_activity($path, 1);
6572 $proj{'age_epoch'} = $val if defined $val;
6574 $$hashref{$path} = \%proj;
6575 return \%proj;
6578 sub git_filter_cached_projects {
6579 my ($cache, $projlist, $verify) = @_;
6580 my $hashref = $$cache[1];
6581 my $sub = $verify ?
6582 sub {verify_cached_project($hashref, $_[0])} :
6583 sub {$$hashref{$_[0]}};
6584 return map {
6585 my $c = &$sub($_->{'path'});
6586 defined $c ? ($_ = $c) : ()
6587 } @$projlist;
6590 # fills project list info (age, description, owner, category, forks, etc.)
6591 # for each project in the list, removing invalid projects from
6592 # returned list, or fill only specified info.
6594 # Invalid projects are removed from the returned list if and only if you
6595 # ask 'age_epoch' to be filled, because they are the only fields
6596 # that run unconditionally git command that requires repository, and
6597 # therefore do always check if project repository is invalid.
6599 # USAGE:
6600 # * fill_project_list_info(\@project_list, 'descr_long', 'ctags')
6601 # ensures that 'descr_long' and 'ctags' fields are filled
6602 # * @project_list = fill_project_list_info(\@project_list)
6603 # ensures that all fields are filled (and invalid projects removed)
6605 # NOTE: modifies $projlist, but does not remove entries from it
6606 sub fill_project_list_info {
6607 my ($projlist, @wanted_keys) = @_;
6609 my $rebuild = @wanted_keys && $wanted_keys[0] eq 'rebuild-cache' && shift @wanted_keys;
6610 return fill_project_list_info_uncached($projlist, @wanted_keys)
6611 unless $projlist_cache_lifetime && $projlist_cache_lifetime > 0;
6613 use File::stat;
6615 my $cache_lifetime = $rebuild ? 0 : $projlist_cache_lifetime;
6616 my $cache_file = "$cache_dir/$projlist_cache_name";
6618 my @projects;
6619 my $stale = 0;
6620 my $now = time();
6621 my $cache_mtime;
6622 if ($cache_lifetime && -f $cache_file) {
6623 $cache_mtime = stat($cache_file)->mtime;
6624 $cache_dump = undef if $cache_mtime &&
6625 (!$cache_dump_mtime || $cache_dump_mtime != $cache_mtime);
6627 if (defined $cache_mtime && # caching is on and $cache_file exists
6628 $cache_mtime + $cache_lifetime*60 > $now &&
6629 ($cache_dump || ($cache_dump = git_retrieve_cache_file($cache_file)))) {
6630 # Cache hit.
6631 $cache_dump_mtime = $cache_mtime;
6632 $stale = $now - $cache_mtime;
6633 my $verify = ($action eq 'summary' || $action eq 'forks') &&
6634 gitweb_check_feature('forks');
6635 @projects = git_filter_cached_projects($cache_dump, $projlist, $verify);
6637 } else { # Cache miss.
6638 if (defined $cache_mtime) {
6639 # Postpone timeout by two minutes so that we get
6640 # enough time to do our job, or to be more exact
6641 # make cache expire after two minutes from now.
6642 my $time = $now - $cache_lifetime*60 + 120;
6643 utime $time, $time, $cache_file;
6645 my @all_projects = git_get_projects_list();
6646 my %all_projects_filled = map { ( $_->{'path'} => $_ ) }
6647 fill_project_list_info_uncached(\@all_projects);
6648 map { $all_projects_filled{$_->{'path'}} = $_ }
6649 filter_forks_from_projects_list([values(%all_projects_filled)])
6650 if gitweb_check_feature('forks');
6651 $cache_dump = [[sort {$a->{'path'} cmp $b->{'path'}} values(%all_projects_filled)],
6652 \%all_projects_filled];
6653 $cache_dump_mtime = git_store_cache_file($cache_file, $cache_dump);
6654 @projects = git_filter_cached_projects($cache_dump, $projlist);
6657 if ($cache_lifetime && $stale > 0) {
6658 print "<div class=\"stale_info\">Cached version (${stale}s old)</div>\n"
6659 unless $shown_stale_message;
6660 $shown_stale_message = 1;
6663 return @projects;
6666 sub fill_project_list_info_uncached {
6667 my ($projlist, @wanted_keys) = @_;
6668 my @projects;
6669 my $filter_set = sub { return @_; };
6670 if (@wanted_keys) {
6671 my %wanted_keys = map { $_ => 1 } @wanted_keys;
6672 $filter_set = sub { return grep { $wanted_keys{$_} } @_; };
6675 my $show_ctags = gitweb_check_feature('ctags');
6676 PROJECT:
6677 foreach my $pr (@$projlist) {
6678 if (project_info_needs_filling($pr, $filter_set->('age_epoch'))) {
6679 my (@activity) = git_get_last_activity($pr->{'path'});
6680 unless (@activity) {
6681 next PROJECT;
6683 ($pr->{'age_epoch'}) = @activity;
6685 if (project_info_needs_filling($pr, $filter_set->('descr', 'descr_long'))) {
6686 my $descr = git_get_project_description($pr->{'path'}) || "";
6687 $descr = to_utf8($descr);
6688 $pr->{'descr_long'} = $descr;
6689 $pr->{'descr'} = chop_str($descr, $projects_list_description_width, 5);
6691 if (project_info_needs_filling($pr, $filter_set->('owner'))) {
6692 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}") || "";
6694 if ($show_ctags &&
6695 project_info_needs_filling($pr, $filter_set->('ctags'))) {
6696 $pr->{'ctags'} = git_get_project_ctags($pr->{'path'});
6698 if ($projects_list_group_categories &&
6699 project_info_needs_filling($pr, $filter_set->('category'))) {
6700 my $cat = git_get_project_category($pr->{'path'}) ||
6701 $project_list_default_category;
6702 $pr->{'category'} = to_utf8($cat);
6705 push @projects, $pr;
6708 return @projects;
6711 sub sort_projects_list {
6712 my ($projlist, $order) = @_;
6714 sub order_str {
6715 my $key = shift;
6716 return sub { lc($a->{$key}) cmp lc($b->{$key}) };
6719 sub order_reverse_num_then_undef {
6720 my $key = shift;
6721 return sub {
6722 defined $a->{$key} ?
6723 (defined $b->{$key} ? $b->{$key} <=> $a->{$key} : -1) :
6724 (defined $b->{$key} ? 1 : 0)
6728 my %orderings = (
6729 project => order_str('path'),
6730 descr => order_str('descr_long'),
6731 owner => order_str('owner'),
6732 age => order_reverse_num_then_undef('age_epoch'),
6735 my $ordering = $orderings{$order};
6736 return defined $ordering ? sort $ordering @$projlist : @$projlist;
6739 # returns a hash of categories, containing the list of project
6740 # belonging to each category
6741 sub build_projlist_by_category {
6742 my ($projlist, $from, $to) = @_;
6743 my %categories;
6745 $from = 0 unless defined $from;
6746 $to = $#$projlist if (!defined $to || $#$projlist < $to);
6748 for (my $i = $from; $i <= $to; $i++) {
6749 my $pr = $projlist->[$i];
6750 push @{$categories{ $pr->{'category'} }}, $pr;
6753 return wantarray ? %categories : \%categories;
6756 # print 'sort by' <th> element, generating 'sort by $name' replay link
6757 # if that order is not selected
6758 sub print_sort_th {
6759 print format_sort_th(@_);
6762 sub format_sort_th {
6763 my ($name, $order, $header) = @_;
6764 my $sort_th = "";
6765 $header ||= ucfirst($name);
6767 if ($order eq $name) {
6768 $sort_th .= "<th>$header</th>\n";
6769 } else {
6770 $sort_th .= "<th>" .
6771 $cgi->a({-href => href(-replay=>1, order=>$name),
6772 -class => "header"}, $header) .
6773 "</th>\n";
6776 return $sort_th;
6779 sub git_project_list_rows {
6780 my ($projlist, $from, $to, $check_forks) = @_;
6782 $from = 0 unless defined $from;
6783 $to = $#$projlist if (!defined $to || $#$projlist < $to);
6785 my $now = time;
6786 my $alternate = 1;
6787 for (my $i = $from; $i <= $to; $i++) {
6788 my $pr = $projlist->[$i];
6790 if ($alternate) {
6791 print "<tr class=\"dark\">\n";
6792 } else {
6793 print "<tr class=\"light\">\n";
6795 $alternate ^= 1;
6797 if ($check_forks) {
6798 print "<td>";
6799 if ($pr->{'forks'}) {
6800 my $nforks = scalar @{$pr->{'forks'}};
6801 my $s = $nforks == 1 ? '' : 's';
6802 if ($nforks > 0) {
6803 print $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks"),
6804 -title => "$nforks fork$s"}, "+");
6805 } else {
6806 print $cgi->span({-title => "$nforks fork$s"}, "+");
6809 print "</td>\n";
6811 my $path = $pr->{'path'};
6812 my $dotgit = $path =~ s/\.git$// ? '.git' : '';
6813 print "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
6814 -class => "list"},
6815 esc_html_match_hl($path, $search_regexp).$dotgit) .
6816 "</td>\n" .
6817 "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
6818 -class => "list",
6819 -title => $pr->{'descr_long'}},
6820 $search_regexp
6821 ? esc_html_match_hl_chopped($pr->{'descr_long'},
6822 $pr->{'descr'}, $search_regexp)
6823 : esc_html($pr->{'descr'})) .
6824 "</td>\n";
6825 unless ($omit_owner) {
6826 print "<td><i>" . ($owner_link_hook
6827 ? $cgi->a({-href => $owner_link_hook->($pr->{'owner'}), -class => "list"},
6828 chop_and_escape_str($pr->{'owner'}, 15))
6829 : chop_and_escape_str($pr->{'owner'}, 15)) . "</i></td>\n";
6831 unless ($omit_age_column) {
6832 my ($age_epoch, $age_string) = ($pr->{'age_epoch'});
6833 $age_string = defined $age_epoch ? age_string($age_epoch, $now) : "No commits";
6834 print "<td class=\"". age_class($age_epoch, $now) . "\">" . $age_string . "</td>\n";
6836 print"<td class=\"link\">" .
6837 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary")}, "summary") . " | " .
6838 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"shortlog")}, "log") . " | " .
6839 $cgi->a({-href => href(project=>$pr->{'path'}, action=>"tree")}, "tree") .
6840 ($pr->{'forks'} ? " | " . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"forks")}, "forks") : '') .
6841 "</td>\n" .
6842 "</tr>\n";
6846 sub git_project_list_body {
6847 # actually uses global variable $project
6848 my ($projlist, $order, $from, $to, $extra, $no_header, $ctags_action, $keep_top) = @_;
6849 my @projects = @$projlist;
6851 my $check_forks = gitweb_check_feature('forks');
6852 my $show_ctags = gitweb_check_feature('ctags');
6853 my $tagfilter = $show_ctags ? $input_params{'ctag_filter'} : undef;
6854 $check_forks = undef
6855 if ($tagfilter || $search_regexp);
6857 # filtering out forks before filling info allows us to do less work
6858 if ($check_forks) {
6859 @projects = filter_forks_from_projects_list(\@projects);
6860 push @projects, { 'path' => "$project_filter.git" }
6861 if $project_filter && $keep_top && is_valid_project("$project_filter.git");
6863 # search_projects_list pre-fills required info
6864 @projects = search_projects_list(\@projects,
6865 'search_regexp' => $search_regexp,
6866 'tagfilter' => $tagfilter)
6867 if ($tagfilter || $search_regexp);
6868 # fill the rest
6869 my @all_fields = ('descr', 'descr_long', 'ctags', 'category');
6870 push @all_fields, 'age_epoch' unless($omit_age_column);
6871 push @all_fields, 'owner' unless($omit_owner);
6872 @projects = fill_project_list_info(\@projects, @all_fields);
6874 $order ||= $default_projects_order;
6875 $from = 0 unless defined $from;
6876 $to = $#projects if (!defined $to || $#projects < $to);
6878 # short circuit
6879 if ($from > $to) {
6880 print "<center>\n".
6881 "<b>No such projects found</b><br />\n".
6882 "Click ".$cgi->a({-href=>href(project=>undef,action=>'project_list')},"here")." to view all projects<br />\n".
6883 "</center>\n<br />\n";
6884 return;
6887 @projects = sort_projects_list(\@projects, $order);
6889 if ($show_ctags) {
6890 my $ctags = git_gather_all_ctags(\@projects);
6891 my $cloud = git_populate_project_tagcloud($ctags, $ctags_action||'project_list');
6892 print git_show_project_tagcloud($cloud, 64);
6895 print "<table class=\"project_list\">\n";
6896 unless ($no_header) {
6897 print "<tr>\n";
6898 if ($check_forks) {
6899 print "<th></th>\n";
6901 print_sort_th('project', $order, 'Project');
6902 print_sort_th('descr', $order, 'Description');
6903 print_sort_th('owner', $order, 'Owner') unless $omit_owner;
6904 print_sort_th('age', $order, 'Last Change') unless $omit_age_column;
6905 print "<th></th>\n" . # for links
6906 "</tr>\n";
6909 if ($projects_list_group_categories) {
6910 # only display categories with projects in the $from-$to window
6911 @projects = sort {$a->{'category'} cmp $b->{'category'}} @projects[$from..$to];
6912 my %categories = build_projlist_by_category(\@projects, $from, $to);
6913 foreach my $cat (sort keys %categories) {
6914 unless ($cat eq "") {
6915 print "<tr>\n";
6916 if ($check_forks) {
6917 print "<td></td>\n";
6919 print "<td class=\"category\" colspan=\"5\">".esc_html($cat)."</td>\n";
6920 print "</tr>\n";
6923 git_project_list_rows($categories{$cat}, undef, undef, $check_forks);
6925 } else {
6926 git_project_list_rows(\@projects, $from, $to, $check_forks);
6929 if (defined $extra) {
6930 print "<tr>\n";
6931 if ($check_forks) {
6932 print "<td></td>\n";
6934 print "<td colspan=\"5\">$extra</td>\n" .
6935 "</tr>\n";
6937 print "</table>\n";
6940 sub git_log_body {
6941 # uses global variable $project
6942 my ($commitlist, $from, $to, $refs, $extra) = @_;
6944 $from = 0 unless defined $from;
6945 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6947 for (my $i = 0; $i <= $to; $i++) {
6948 my %co = %{$commitlist->[$i]};
6949 next if !%co;
6950 my $commit = $co{'id'};
6951 my $ref = format_ref_marker($refs, $commit);
6952 git_print_header_div('commit',
6953 "<span class=\"age\">$co{'age_string'}</span>" .
6954 esc_html($co{'title'}),
6955 $commit, undef, $ref);
6956 print "<div class=\"title_text\">\n" .
6957 "<div class=\"log_link\">\n" .
6958 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") .
6959 " | " .
6960 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") .
6961 " | " .
6962 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree") .
6963 "<br/>\n" .
6964 "</div>\n";
6965 git_print_authorship(\%co, -tag => 'span');
6966 print "<br/>\n</div>\n";
6968 print "<div class=\"log_body\">\n";
6969 git_print_log($co{'comment'}, -final_empty_line=> 1);
6970 print "</div>\n";
6972 if ($extra) {
6973 print "<div class=\"page_nav\">\n";
6974 print "$extra\n";
6975 print "</div>\n";
6979 sub git_shortlog_body {
6980 # uses global variable $project
6981 my ($commitlist, $from, $to, $refs, $extra) = @_;
6983 $from = 0 unless defined $from;
6984 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
6986 print "<table class=\"shortlog\">\n";
6987 my $alternate = 1;
6988 for (my $i = $from; $i <= $to; $i++) {
6989 my %co = %{$commitlist->[$i]};
6990 my $commit = $co{'id'};
6991 my $ref = format_ref_marker($refs, $commit);
6992 if ($alternate) {
6993 print "<tr class=\"dark\">\n";
6994 } else {
6995 print "<tr class=\"light\">\n";
6997 $alternate ^= 1;
6998 # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
6999 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
7000 format_author_html('td', \%co, 10) . "<td>";
7001 print format_subject_html($co{'title'}, $co{'title_short'},
7002 href(action=>"commit", hash=>$commit), $ref);
7003 print "</td>\n" .
7004 "<td class=\"link\">" .
7005 $cgi->a({-href => href(action=>"commit", hash=>$commit)}, "commit") . " | " .
7006 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff") . " | " .
7007 $cgi->a({-href => href(action=>"tree", hash=>$commit, hash_base=>$commit)}, "tree");
7008 my $snapshot_links = format_snapshot_links($commit);
7009 if (defined $snapshot_links) {
7010 print " | " . $snapshot_links;
7012 print "</td>\n" .
7013 "</tr>\n";
7015 if (defined $extra) {
7016 print "<tr>\n" .
7017 "<td colspan=\"4\">$extra</td>\n" .
7018 "</tr>\n";
7020 print "</table>\n";
7023 sub git_history_body {
7024 # Warning: assumes constant type (blob or tree) during history
7025 my ($commitlist, $from, $to, $refs, $extra,
7026 $file_name, $file_hash, $ftype) = @_;
7028 $from = 0 unless defined $from;
7029 $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
7031 print "<table class=\"history\">\n";
7032 my $alternate = 1;
7033 for (my $i = $from; $i <= $to; $i++) {
7034 my %co = %{$commitlist->[$i]};
7035 if (!%co) {
7036 next;
7038 my $commit = $co{'id'};
7040 my $ref = format_ref_marker($refs, $commit);
7042 if ($alternate) {
7043 print "<tr class=\"dark\">\n";
7044 } else {
7045 print "<tr class=\"light\">\n";
7047 $alternate ^= 1;
7048 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
7049 # shortlog: format_author_html('td', \%co, 10)
7050 format_author_html('td', \%co, 15, 3) . "<td>";
7051 # originally git_history used chop_str($co{'title'}, 50)
7052 print format_subject_html($co{'title'}, $co{'title_short'},
7053 href(action=>"commit", hash=>$commit), $ref);
7054 print "</td>\n" .
7055 "<td class=\"link\">" .
7056 $cgi->a({-href => href(action=>$ftype, hash_base=>$commit, file_name=>$file_name)}, $ftype) . " | " .
7057 $cgi->a({-href => href(action=>"commitdiff", hash=>$commit)}, "commitdiff");
7059 if ($ftype eq 'blob') {
7060 my $blob_current = $file_hash;
7061 my $blob_parent = git_get_hash_by_path($commit, $file_name);
7062 if (defined $blob_current && defined $blob_parent &&
7063 $blob_current ne $blob_parent) {
7064 print " | " .
7065 $cgi->a({-href => href(action=>"blobdiff",
7066 hash=>$blob_current, hash_parent=>$blob_parent,
7067 hash_base=>$hash_base, hash_parent_base=>$commit,
7068 file_name=>$file_name)},
7069 "diff to current");
7072 print "</td>\n" .
7073 "</tr>\n";
7075 if (defined $extra) {
7076 print "<tr>\n" .
7077 "<td colspan=\"4\">$extra</td>\n" .
7078 "</tr>\n";
7080 print "</table>\n";
7083 sub git_tags_body {
7084 # uses global variable $project
7085 my ($taglist, $from, $to, $extra, $head_at, $full, $order) = @_;
7086 $from = 0 unless defined $from;
7087 $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
7088 $order ||= $default_refs_order;
7090 print "<table class=\"tags\">\n";
7091 if ($full) {
7092 print "<tr class=\"tags_header\">\n";
7093 print_sort_th('age', $order, 'Last Change');
7094 print_sort_th('name', $order, 'Name');
7095 print "<th></th>\n" . # for comment
7096 "<th></th>\n" . # for tag
7097 "<th></th>\n" . # for links
7098 "</tr>\n";
7100 my $alternate = 1;
7101 for (my $i = $from; $i <= $to; $i++) {
7102 my $entry = $taglist->[$i];
7103 my %tag = %$entry;
7104 my $comment = $tag{'subject'};
7105 my $comment_short;
7106 if (defined $comment) {
7107 $comment_short = chop_str($comment, 30, 5);
7109 my $curr = defined $head_at && $tag{'id'} eq $head_at;
7110 if ($alternate) {
7111 print "<tr class=\"dark\">\n";
7112 } else {
7113 print "<tr class=\"light\">\n";
7115 $alternate ^= 1;
7116 if (defined $tag{'age'}) {
7117 print "<td><i>$tag{'age'}</i></td>\n";
7118 } else {
7119 print "<td></td>\n";
7121 print(($curr ? "<td class=\"current_head\">" : "<td>") .
7122 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'}),
7123 -class => "list name"}, esc_html($tag{'name'})) .
7124 "</td>\n" .
7125 "<td>");
7126 if (defined $comment) {
7127 print format_subject_html($comment, $comment_short,
7128 href(action=>"tag", hash=>$tag{'id'}));
7130 print "</td>\n" .
7131 "<td class=\"selflink\">";
7132 if ($tag{'type'} eq "tag") {
7133 print $cgi->a({-href => href(action=>"tag", hash=>$tag{'id'})}, "tag");
7134 } else {
7135 print "&#160;";
7137 print "</td>\n" .
7138 "<td class=\"link\">" . " | " .
7139 $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
7140 if ($tag{'reftype'} eq "commit") {
7141 print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "log");
7142 print " | " . $cgi->a({-href => href(action=>"tree", hash=>$tag{'fullname'})}, "tree") if $full;
7143 } elsif ($tag{'reftype'} eq "blob") {
7144 print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
7146 print "</td>\n" .
7147 "</tr>";
7149 if (defined $extra) {
7150 print "<tr>\n" .
7151 "<td colspan=\"5\">$extra</td>\n" .
7152 "</tr>\n";
7154 print "</table>\n";
7157 sub git_heads_body {
7158 # uses global variable $project
7159 my ($headlist, $head_at, $from, $to, $extra) = @_;
7160 $from = 0 unless defined $from;
7161 $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
7163 print "<table class=\"heads\">\n";
7164 my $alternate = 1;
7165 for (my $i = $from; $i <= $to; $i++) {
7166 my $entry = $headlist->[$i];
7167 my %ref = %$entry;
7168 my $curr = defined $head_at && $ref{'id'} eq $head_at;
7169 if ($alternate) {
7170 print "<tr class=\"dark\">\n";
7171 } else {
7172 print "<tr class=\"light\">\n";
7174 $alternate ^= 1;
7175 print "<td><i>$ref{'age'}</i></td>\n" .
7176 ($curr ? "<td class=\"current_head\">" : "<td>") .
7177 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
7178 -class => "list name"},esc_html($ref{'name'})) .
7179 "</td>\n" .
7180 "<td class=\"link\">" .
7181 $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "log") . " | " .
7182 $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'fullname'})}, "tree") .
7183 "</td>\n" .
7184 "</tr>";
7186 if (defined $extra) {
7187 print "<tr>\n" .
7188 "<td colspan=\"3\">$extra</td>\n" .
7189 "</tr>\n";
7191 print "</table>\n";
7194 # Display a single remote block
7195 sub git_remote_block {
7196 my ($remote, $rdata, $limit, $head) = @_;
7198 my $heads = $rdata->{'heads'};
7199 my $fetch = $rdata->{'fetch'};
7200 my $push = $rdata->{'push'};
7202 my $urls_table = "<table class=\"projects_list\">\n" ;
7204 if (defined $fetch) {
7205 if ($fetch eq $push) {
7206 $urls_table .= format_repo_url("URL", $fetch);
7207 } else {
7208 $urls_table .= format_repo_url("Fetch&#160;URL", $fetch);
7209 $urls_table .= format_repo_url("Push&#160;URL", $push) if defined $push;
7211 } elsif (defined $push) {
7212 $urls_table .= format_repo_url("Push&#160;URL", $push);
7213 } else {
7214 $urls_table .= format_repo_url("", "No remote URL");
7217 $urls_table .= "</table>\n";
7219 my $dots;
7220 if (defined $limit && $limit < @$heads) {
7221 $dots = $cgi->a({-href => href(action=>"remotes", hash=>$remote)}, "...");
7224 print $urls_table;
7225 git_heads_body($heads, $head, 0, $limit, $dots);
7228 # Display a list of remote names with the respective fetch and push URLs
7229 sub git_remotes_list {
7230 my ($remotedata, $limit) = @_;
7231 print "<table class=\"heads\">\n";
7232 my $alternate = 1;
7233 my @remotes = sort keys %$remotedata;
7235 my $limited = $limit && $limit < @remotes;
7237 $#remotes = $limit - 1 if $limited;
7239 while (my $remote = shift @remotes) {
7240 my $rdata = $remotedata->{$remote};
7241 my $fetch = $rdata->{'fetch'};
7242 my $push = $rdata->{'push'};
7243 if ($alternate) {
7244 print "<tr class=\"dark\">\n";
7245 } else {
7246 print "<tr class=\"light\">\n";
7248 $alternate ^= 1;
7249 print "<td>" .
7250 $cgi->a({-href=> href(action=>'remotes', hash=>$remote),
7251 -class=> "list name"},esc_html($remote)) .
7252 "</td>";
7253 print "<td class=\"link\">" .
7254 (defined $fetch ? $cgi->a({-href=> $fetch}, "fetch") : "fetch") .
7255 " | " .
7256 (defined $push ? $cgi->a({-href=> $push}, "push") : "push") .
7257 "</td>";
7259 print "</tr>\n";
7262 if ($limited) {
7263 print "<tr>\n" .
7264 "<td colspan=\"3\">" .
7265 $cgi->a({-href => href(action=>"remotes")}, "...") .
7266 "</td>\n" . "</tr>\n";
7269 print "</table>";
7272 # Display remote heads grouped by remote, unless there are too many
7273 # remotes, in which case we only display the remote names
7274 sub git_remotes_body {
7275 my ($remotedata, $limit, $head) = @_;
7276 if ($limit and $limit < keys %$remotedata) {
7277 git_remotes_list($remotedata, $limit);
7278 } else {
7279 fill_remote_heads($remotedata);
7280 while (my ($remote, $rdata) = each %$remotedata) {
7281 git_print_section({-class=>"remote", -id=>$remote},
7282 ["remotes", $remote, $remote], sub {
7283 git_remote_block($remote, $rdata, $limit, $head);
7289 sub git_search_message {
7290 my %co = @_;
7292 my $greptype;
7293 if ($searchtype eq 'commit') {
7294 $greptype = "--grep=";
7295 } elsif ($searchtype eq 'author') {
7296 $greptype = "--author=";
7297 } elsif ($searchtype eq 'committer') {
7298 $greptype = "--committer=";
7300 $greptype .= $searchtext;
7301 my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
7302 $greptype, '--regexp-ignore-case',
7303 $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
7305 my $paging_nav = '';
7306 if ($page > 0) {
7307 $paging_nav .=
7308 $cgi->a({-href => href(-replay=>1, page=>undef)},
7309 "first") .
7310 " &#183; " .
7311 $cgi->a({-href => href(-replay=>1, page=>$page-1),
7312 -accesskey => "p", -title => "Alt-p"}, "prev");
7313 } else {
7314 $paging_nav .= "first &#183; prev";
7316 my $next_link = '';
7317 if ($#commitlist >= 100) {
7318 $next_link =
7319 $cgi->a({-href => href(-replay=>1, page=>$page+1),
7320 -accesskey => "n", -title => "Alt-n"}, "next");
7321 $paging_nav .= " &#183; $next_link";
7322 } else {
7323 $paging_nav .= " &#183; next";
7326 git_header_html();
7328 git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
7329 git_print_header_div('commit', esc_html($co{'title'}), $hash);
7330 if ($page == 0 && !@commitlist) {
7331 print "<p>No match.</p>\n";
7332 } else {
7333 git_search_grep_body(\@commitlist, 0, 99, $next_link);
7336 git_footer_html();
7339 sub git_search_changes {
7340 my %co = @_;
7342 local $/ = "\n";
7343 defined(my $fd = git_cmd_pipe '--no-pager', 'log', @diff_opts,
7344 '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
7345 ($search_use_regexp ? '--pickaxe-regex' : ()))
7346 or die_error(500, "Open git-log failed");
7348 git_header_html();
7350 git_print_page_nav('','', $hash,$co{'tree'},$hash);
7351 git_print_header_div('commit', esc_html($co{'title'}), $hash);
7353 print "<table class=\"pickaxe search\">\n";
7354 my $alternate = 1;
7355 undef %co;
7356 my @files;
7357 while (my $line = to_utf8(scalar <$fd>)) {
7358 chomp $line;
7359 next unless $line;
7361 my %set = parse_difftree_raw_line($line);
7362 if (defined $set{'commit'}) {
7363 # finish previous commit
7364 if (%co) {
7365 print "</td>\n" .
7366 "<td class=\"link\">" .
7367 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
7368 "commit") .
7369 " | " .
7370 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
7371 hash_base=>$co{'id'})},
7372 "tree") .
7373 "</td>\n" .
7374 "</tr>\n";
7377 if ($alternate) {
7378 print "<tr class=\"dark\">\n";
7379 } else {
7380 print "<tr class=\"light\">\n";
7382 $alternate ^= 1;
7383 %co = parse_commit($set{'commit'});
7384 my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
7385 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
7386 "<td><i>$author</i></td>\n" .
7387 "<td>" .
7388 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
7389 -class => "list subject"},
7390 chop_and_escape_str($co{'title'}, 50) . "<br/>");
7391 } elsif (defined $set{'to_id'}) {
7392 next if ($set{'to_id'} =~ m/^0{40}$/);
7394 print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
7395 hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
7396 -class => "list"},
7397 "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
7398 "<br/>\n";
7401 close $fd;
7403 # finish last commit (warning: repetition!)
7404 if (%co) {
7405 print "</td>\n" .
7406 "<td class=\"link\">" .
7407 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})},
7408 "commit") .
7409 " | " .
7410 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'},
7411 hash_base=>$co{'id'})},
7412 "tree") .
7413 "</td>\n" .
7414 "</tr>\n";
7417 print "</table>\n";
7419 git_footer_html();
7422 sub git_search_files {
7423 my %co = @_;
7425 local $/ = "\n";
7426 defined(my $fd = git_cmd_pipe 'grep', '-n', '-z',
7427 $search_use_regexp ? ('-E', '-i') : '-F',
7428 $searchtext, $co{'tree'})
7429 or die_error(500, "Open git-grep failed");
7431 git_header_html();
7433 git_print_page_nav('','', $hash,$co{'tree'},$hash);
7434 git_print_header_div('commit', esc_html($co{'title'}), $hash);
7436 print "<table class=\"grep_search\">\n";
7437 my $alternate = 1;
7438 my $matches = 0;
7439 my $lastfile = '';
7440 my $file_href;
7441 while (my $line = to_utf8(scalar <$fd>)) {
7442 chomp $line;
7443 my ($file, $lno, $ltext, $binary);
7444 last if ($matches++ > 1000);
7445 if ($line =~ /^Binary file (.+) matches$/) {
7446 $file = $1;
7447 $binary = 1;
7448 } else {
7449 ($file, $lno, $ltext) = split(/\0/, $line, 3);
7450 $file =~ s/^$co{'tree'}://;
7452 if ($file ne $lastfile) {
7453 $lastfile and print "</td></tr>\n";
7454 if ($alternate++) {
7455 print "<tr class=\"dark\">\n";
7456 } else {
7457 print "<tr class=\"light\">\n";
7459 $file_href = href(action=>"blob", hash_base=>$co{'id'},
7460 file_name=>$file);
7461 print "<td class=\"list\">".
7462 $cgi->a({-href => $file_href, -class => "list"}, esc_path($file));
7463 print "</td><td>\n";
7464 $lastfile = $file;
7466 if ($binary) {
7467 print "<div class=\"binary\">Binary file</div>\n";
7468 } else {
7469 $ltext = untabify($ltext);
7470 if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
7471 $ltext = esc_html($1, -nbsp=>1);
7472 $ltext .= '<span class="match">';
7473 $ltext .= esc_html($2, -nbsp=>1);
7474 $ltext .= '</span>';
7475 $ltext .= esc_html($3, -nbsp=>1);
7476 } else {
7477 $ltext = esc_html($ltext, -nbsp=>1);
7479 print "<div class=\"pre\">" .
7480 $cgi->a({-href => $file_href.'#l'.$lno,
7481 -class => "linenr"}, sprintf('%4i', $lno)) .
7482 ' ' . $ltext . "</div>\n";
7485 if ($lastfile) {
7486 print "</td></tr>\n";
7487 if ($matches > 1000) {
7488 print "<div class=\"diff nodifferences\">Too many matches, listing trimmed</div>\n";
7490 } else {
7491 print "<div class=\"diff nodifferences\">No matches found</div>\n";
7493 close $fd;
7495 print "</table>\n";
7497 git_footer_html();
7500 sub git_search_grep_body {
7501 my ($commitlist, $from, $to, $extra) = @_;
7502 $from = 0 unless defined $from;
7503 $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
7505 print "<table class=\"commit_search\">\n";
7506 my $alternate = 1;
7507 for (my $i = $from; $i <= $to; $i++) {
7508 my %co = %{$commitlist->[$i]};
7509 if (!%co) {
7510 next;
7512 my $commit = $co{'id'};
7513 if ($alternate) {
7514 print "<tr class=\"dark\">\n";
7515 } else {
7516 print "<tr class=\"light\">\n";
7518 $alternate ^= 1;
7519 print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
7520 format_author_html('td', \%co, 15, 5) .
7521 "<td>" .
7522 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
7523 -class => "list subject"},
7524 chop_and_escape_str($co{'title'}, 50) . "<br/>");
7525 my $comment = $co{'comment'};
7526 foreach my $line (@$comment) {
7527 if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
7528 my ($lead, $match, $trail) = ($1, $2, $3);
7529 $match = chop_str($match, 70, 5, 'center');
7530 my $contextlen = int((80 - length($match))/2);
7531 $contextlen = 30 if ($contextlen > 30);
7532 $lead = chop_str($lead, $contextlen, 10, 'left');
7533 $trail = chop_str($trail, $contextlen, 10, 'right');
7535 $lead = esc_html($lead);
7536 $match = esc_html($match);
7537 $trail = esc_html($trail);
7539 print "$lead<span class=\"match\">$match</span>$trail<br />";
7542 print "</td>\n" .
7543 "<td class=\"link\">" .
7544 $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
7545 " | " .
7546 $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
7547 " | " .
7548 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
7549 print "</td>\n" .
7550 "</tr>\n";
7552 if (defined $extra) {
7553 print "<tr>\n" .
7554 "<td colspan=\"3\">$extra</td>\n" .
7555 "</tr>\n";
7557 print "</table>\n";
7560 ## ======================================================================
7561 ## ======================================================================
7562 ## actions
7564 sub git_project_list_load {
7565 my $empty_list_ok = shift;
7566 my $order = $input_params{'order'};
7567 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
7568 die_error(400, "Unknown order parameter");
7571 my @list = git_get_projects_list($project_filter, $strict_export);
7572 if ($project_filter && (!@list || !gitweb_check_feature('forks'))) {
7573 push @list, { 'path' => "$project_filter.git" }
7574 if is_valid_project("$project_filter.git");
7576 if (!@list) {
7577 die_error(404, "No projects found") unless $empty_list_ok;
7580 return (\@list, $order);
7583 sub git_frontpage {
7584 my ($projlist, $order);
7586 if ($frontpage_no_project_list) {
7587 $project = undef;
7588 $project_filter = undef;
7589 } else {
7590 ($projlist, $order) = git_project_list_load(1);
7592 git_header_html();
7593 if (defined $home_text && -f $home_text) {
7594 print "<div class=\"index_include\">\n";
7595 insert_file($home_text);
7596 print "</div>\n";
7598 git_project_search_form($searchtext, $search_use_regexp);
7599 if ($frontpage_no_project_list) {
7600 my $show_ctags = gitweb_check_feature('ctags');
7601 if ($frontpage_no_project_list == 1 and $show_ctags) {
7602 my @projects = git_get_projects_list($project_filter, $strict_export);
7603 @projects = filter_forks_from_projects_list(\@projects) if gitweb_check_feature('forks');
7604 @projects = fill_project_list_info(\@projects, 'ctags');
7605 my $ctags = git_gather_all_ctags(\@projects);
7606 my $cloud = git_populate_project_tagcloud($ctags, 'project_list');
7607 print git_show_project_tagcloud($cloud, 64);
7609 } else {
7610 git_project_list_body($projlist, $order, undef, undef, undef, undef, undef, 1);
7612 git_footer_html();
7615 sub git_project_list {
7616 my ($projlist, $order) = git_project_list_load();
7617 git_header_html();
7618 if (!$frontpage_no_project_list && defined $home_text && -f $home_text) {
7619 print "<div class=\"index_include\">\n";
7620 insert_file($home_text);
7621 print "</div>\n";
7623 git_project_search_form();
7624 git_project_list_body($projlist, $order, undef, undef, undef, undef, undef, 1);
7625 git_footer_html();
7628 sub git_forks {
7629 my $order = $input_params{'order'};
7630 if (defined $order && $order !~ m/none|project|descr|owner|age/) {
7631 die_error(400, "Unknown order parameter");
7634 my $filter = $project;
7635 $filter =~ s/\.git$//;
7636 my @list = git_get_projects_list($filter);
7637 if (!@list) {
7638 die_error(404, "No forks found");
7641 git_header_html();
7642 git_print_page_nav('','');
7643 git_print_header_div('summary', "$project forks");
7644 git_project_list_body(\@list, $order, undef, undef, undef, undef, 'forks');
7645 git_footer_html();
7648 sub git_project_index {
7649 my @projects = git_get_projects_list($project_filter, $strict_export);
7650 if (!@projects) {
7651 die_error(404, "No projects found");
7654 print $cgi->header(
7655 -type => 'text/plain',
7656 -charset => 'utf-8',
7657 -content_disposition => 'inline; filename="index.aux"');
7659 foreach my $pr (@projects) {
7660 if (!exists $pr->{'owner'}) {
7661 $pr->{'owner'} = git_get_project_owner("$pr->{'path'}");
7664 my ($path, $owner) = ($pr->{'path'}, $pr->{'owner'});
7665 # quote as in CGI::Util::encode, but keep the slash, and use '+' for ' '
7666 $path =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
7667 $owner =~ s/([^a-zA-Z0-9_.\-\/ ])/sprintf("%%%02X", ord($1))/eg;
7668 $path =~ s/ /\+/g;
7669 $owner =~ s/ /\+/g;
7671 print "$path $owner\n";
7675 sub git_summary {
7676 my $descr = git_get_project_description($project) || "none";
7677 my %co = parse_commit("HEAD");
7678 my %cd = %co ? parse_date($co{'committer_epoch'}, $co{'committer_tz'}) : ();
7679 my $head = $co{'id'};
7680 my $remote_heads = gitweb_check_feature('remote_heads');
7682 my $owner = git_get_project_owner($project);
7683 my $homepage = git_get_project_config('homepage');
7684 my $base_url = git_get_project_config('baseurl');
7685 my $last_refresh = git_get_project_config('lastrefresh');
7687 my $refs = git_get_references();
7688 # These get_*_list functions return one more to allow us to see if
7689 # there are more ...
7690 my @taglist = git_get_tags_list(16);
7691 my @headlist = git_get_heads_list(16);
7692 my %remotedata = $remote_heads ? git_get_remotes_list() : ();
7693 my @forklist;
7694 my $check_forks = gitweb_check_feature('forks');
7696 if ($check_forks) {
7697 # find forks of a project
7698 my $filter = $project;
7699 $filter =~ s/\.git$//;
7700 @forklist = git_get_projects_list($filter);
7701 # filter out forks of forks
7702 @forklist = filter_forks_from_projects_list(\@forklist)
7703 if (@forklist);
7706 git_header_html();
7707 git_print_page_nav('summary','', $head);
7709 if ($check_forks and $project =~ m#/#) {
7710 my $xproject = $project; $xproject =~ s#/[^/]+$#.git#; #
7711 my $r = $cgi->a({-href=> href(project => $xproject, action => 'summary')}, $xproject);
7712 print <<EOT;
7713 <div class="forkinfo">
7714 This project is a fork of the $r project. If you have that one
7715 already cloned locally, you can use
7716 <pre>git clone --reference /path/to/your/$xproject/incarnation mirror_URL</pre>
7717 to save bandwidth during cloning.
7718 </div>
7722 print "<div class=\"title\">&#160;</div>\n";
7723 print "<table class=\"projects_list\">\n" .
7724 "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n";
7725 if ($homepage) {
7726 print "<tr id=\"metadata_homepage\"><td>homepage&#160;URL</td><td>" . $cgi->a({-href => $homepage}, $homepage) . "</td></tr>\n";
7728 if ($base_url) {
7729 print "<tr id=\"metadata_baseurl\"><td>repository&#160;URL</td><td>" . esc_html($base_url) . "</td></tr>\n";
7731 if ($owner and not $omit_owner) {
7732 print "<tr id=\"metadata_owner\"><td>owner</td><td>" . ($owner_link_hook
7733 ? $cgi->a({-href => $owner_link_hook->($owner)}, email_obfuscate($owner))
7734 : email_obfuscate($owner)) . "</td></tr>\n";
7736 if (defined $cd{'rfc2822'}) {
7737 print "<tr id=\"metadata_lchange\"><td>last&#160;change</td>" .
7738 "<td>".format_timestamp_html(\%cd)."</td></tr>\n";
7740 if (defined $last_refresh) {
7741 my %rd = parse_date_rfc2822($last_refresh);
7742 print "<tr id=\"metadata_lrefresh\"><td>last&#160;refresh</td>" .
7743 "<td>".format_timestamp_html(\%rd)."</td></tr>\n"
7744 if defined $rd{'rfc2822'};
7747 # use per project git URL list in $projectroot/$project/cloneurl
7748 # or make project git URL from git base URL and project name
7749 my $url_tag = $base_url ? "mirror&#160;URL" : "URL";
7750 my @url_list = git_get_project_url_list($project);
7751 @url_list = map { "$_/$project" } @git_base_url_list unless @url_list;
7752 foreach my $git_url (@url_list) {
7753 next unless $git_url;
7754 print format_repo_url($url_tag, $git_url);
7755 $url_tag = "";
7757 @url_list = map { "$_/$project" } @git_base_push_urls;
7758 if ((git_get_project_config("showpush", '--bool')||'false') eq "true" ||
7759 -f "$projectroot/$project/.nofetch") {
7760 $url_tag = "Push&#160;URL";
7761 foreach my $git_push_url (@url_list) {
7762 next unless $git_push_url;
7763 my $hint = $https_hint_html && $git_push_url =~ /^https:/i ?
7764 "&#160;$https_hint_html" : '';
7765 print "<tr class=\"metadata_pushurl\"><td>$url_tag</td><td>$git_push_url$hint</td></tr>\n";
7766 $url_tag = "";
7770 # Tag cloud
7771 my $show_ctags = gitweb_check_feature('ctags');
7772 if ($show_ctags) {
7773 my $ctags = git_get_project_ctags($project);
7774 if (%$ctags || $show_ctags !~ /^\d+$/) {
7775 # without ability to add tags, don't show if there are none
7776 my $cloud = git_populate_project_tagcloud($ctags, 'project_list');
7777 print "<tr id=\"metadata_ctags\">" .
7778 "<td style=\"vertical-align:middle\">content&#160;tags<br />";
7779 print "</td>\n<td>" unless %$ctags;
7780 print "<form action=\"$show_ctags\" method=\"post\" style=\"white-space:nowrap\">" .
7781 "<input type=\"hidden\" name=\"p\" value=\"$project\"/>" .
7782 "add: <input type=\"text\" name=\"t\" size=\"8\" /></form>"
7783 unless $show_ctags =~ /^\d+$/;
7784 print "</td>\n<td>" if %$ctags;
7785 print git_show_project_tagcloud($cloud, 48)."</td>" .
7786 "</tr>\n";
7790 print "</table>\n";
7792 # If XSS prevention is on, we don't include README.html.
7793 # TODO: Allow a readme in some safe format.
7794 if (!$prevent_xss && -s "$projectroot/$project/README.html") {
7795 print "<div class=\"title\">readme</div>\n" .
7796 "<div class=\"readme\">\n";
7797 insert_file("$projectroot/$project/README.html");
7798 print "\n</div>\n"; # class="readme"
7801 # we need to request one more than 16 (0..15) to check if
7802 # those 16 are all
7803 my @commitlist = $head ? parse_commits($head, 17) : ();
7804 if (@commitlist) {
7805 git_print_header_div('shortlog');
7806 git_shortlog_body(\@commitlist, 0, 15, $refs,
7807 $#commitlist <= 15 ? undef :
7808 $cgi->a({-href => href(action=>"shortlog")}, "..."));
7811 if (@taglist) {
7812 git_print_header_div('tags');
7813 git_tags_body(\@taglist, 0, 15,
7814 $#taglist <= 15 ? undef :
7815 $cgi->a({-href => href(action=>"tags")}, "..."));
7818 if (@headlist) {
7819 git_print_header_div('heads');
7820 git_heads_body(\@headlist, $head, 0, 15,
7821 $#headlist <= 15 ? undef :
7822 $cgi->a({-href => href(action=>"heads")}, "..."));
7825 if (%remotedata) {
7826 git_print_header_div('remotes');
7827 git_remotes_body(\%remotedata, 15, $head);
7830 if (@forklist) {
7831 git_print_header_div('forks');
7832 git_project_list_body(\@forklist, 'age', 0, 15,
7833 $#forklist <= 15 ? undef :
7834 $cgi->a({-href => href(action=>"forks")}, "..."),
7835 'no_header', 'forks');
7838 git_footer_html();
7841 sub git_tag {
7842 my %tag = parse_tag($hash);
7844 if (! %tag) {
7845 die_error(404, "Unknown tag object");
7848 my $fullhash;
7849 $fullhash = $hash if $hash =~ m/^[0-9a-fA-F]{40}$/;
7850 $fullhash = git_get_full_hash($project, $hash) unless $fullhash;
7852 my $head = git_get_head_hash($project);
7853 git_header_html();
7854 git_print_page_nav('','', $head,undef,$head);
7855 git_print_header_div('commit', esc_html($tag{'name'}), $hash);
7856 print "<div class=\"title_text\">\n" .
7857 "<table class=\"object_header\">\n" .
7858 "<tr><td>tag</td><td class=\"sha1\">$fullhash</td></tr>\n" .
7859 "<tr>\n" .
7860 "<td>object</td>\n" .
7861 "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
7862 $tag{'object'}) . "</td>\n" .
7863 "<td class=\"link\">" . $cgi->a({-href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
7864 $tag{'type'}) . "</td>\n" .
7865 "</tr>\n";
7866 if (defined($tag{'author'})) {
7867 git_print_authorship_rows(\%tag, 'author');
7869 print "</table>\n\n" .
7870 "</div>\n";
7871 print "<div class=\"page_body\">";
7872 my $comment = $tag{'comment'};
7873 foreach my $line (@$comment) {
7874 chomp $line;
7875 print esc_html($line, -nbsp=>1) . "<br/>\n";
7877 print "</div>\n";
7878 git_footer_html();
7881 sub git_blame_common {
7882 my $format = shift || 'porcelain';
7883 if ($format eq 'porcelain' && $input_params{'javascript'}) {
7884 $format = 'incremental';
7885 $action = 'blame_incremental'; # for page title etc
7888 # permissions
7889 gitweb_check_feature('blame')
7890 or die_error(403, "Blame view not allowed");
7892 # error checking
7893 die_error(400, "No file name given") unless $file_name;
7894 $hash_base ||= git_get_head_hash($project);
7895 die_error(404, "Couldn't find base commit") unless $hash_base;
7896 my %co = parse_commit($hash_base)
7897 or die_error(404, "Commit not found");
7898 my $ftype = "blob";
7899 if (!defined $hash) {
7900 $hash = git_get_hash_by_path($hash_base, $file_name, "blob")
7901 or die_error(404, "Error looking up file");
7902 } else {
7903 $ftype = git_get_type($hash);
7904 if ($ftype !~ "blob") {
7905 die_error(400, "Object is not a blob");
7909 my $fd;
7910 if ($format eq 'incremental') {
7911 # get file contents (as base)
7912 defined($fd = git_cmd_pipe 'cat-file', 'blob', $hash)
7913 or die_error(500, "Open git-cat-file failed");
7914 } elsif ($format eq 'data') {
7915 # run git-blame --incremental
7916 defined($fd = git_cmd_pipe "blame", "--incremental",
7917 $hash_base, "--", $file_name)
7918 or die_error(500, "Open git-blame --incremental failed");
7919 } else {
7920 # run git-blame --porcelain
7921 defined($fd = git_cmd_pipe "blame", '-p',
7922 $hash_base, '--', $file_name)
7923 or die_error(500, "Open git-blame --porcelain failed");
7926 # incremental blame data returns early
7927 if ($format eq 'data') {
7928 print $cgi->header(
7929 -type=>"text/plain", -charset => "utf-8",
7930 -status=> "200 OK");
7931 local $| = 1; # output autoflush
7932 while (<$fd>) {
7933 print to_utf8($_);
7935 close $fd
7936 or print "ERROR $!\n";
7938 print 'END';
7939 if (defined $t0 && gitweb_check_feature('timed')) {
7940 print ' '.
7941 tv_interval($t0, [ gettimeofday() ]).
7942 ' '.$number_of_git_cmds;
7944 print "\n";
7946 return;
7949 # page header
7950 git_header_html();
7951 my $formats_nav =
7952 $cgi->a({-href => href(action=>"blob", -replay=>1)},
7953 "blob");
7954 $formats_nav .=
7955 " | " .
7956 $cgi->a({-href => href(action=>"history", -replay=>1)},
7957 "history") .
7958 " | " .
7959 $cgi->a({-href => href(action=>$action, file_name=>$file_name)},
7960 "HEAD");
7961 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
7962 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
7963 git_print_page_path($file_name, $ftype, $hash_base);
7965 # page body
7966 if ($format eq 'incremental') {
7967 print "<noscript>\n<div class=\"error\"><center><b>\n".
7968 "This page requires JavaScript to run.\n Use ".
7969 $cgi->a({-href => href(action=>'blame',javascript=>0,-replay=>1)},
7970 'this page').
7971 " instead.\n".
7972 "</b></center></div>\n</noscript>\n";
7974 print qq!<div id="progress_bar" style="width: 100%; background-color: yellow"></div>\n!;
7977 print qq!<div class="page_body">\n!;
7978 print qq!<div id="progress_info">... / ...</div>\n!
7979 if ($format eq 'incremental');
7980 print qq!<table id="blame_table" class="blame" width="100%">\n!.
7981 #qq!<col width="5.5em" /><col width="2.5em" /><col width="*" />\n!.
7982 qq!<thead>\n!.
7983 qq!<tr><th nowrap="nowrap" style="white-space:nowrap">!.
7984 qq!Commit&#160;<a href="javascript:extra_blame_columns()" id="columns_expander" !.
7985 qq!title="toggles blame author information display">[+]</a></th>!.
7986 qq!<th class="extra_column">Author</th><th class="extra_column">Date</th>!.
7987 qq!<th>Line</th><th width="100%">Data</th></tr>\n!.
7988 qq!</thead>\n!.
7989 qq!<tbody>\n!;
7991 my @rev_color = qw(light dark);
7992 my $num_colors = scalar(@rev_color);
7993 my $current_color = 0;
7995 if ($format eq 'incremental') {
7996 my $color_class = $rev_color[$current_color];
7998 #contents of a file
7999 my $linenr = 0;
8000 LINE:
8001 while (my $line = to_utf8(scalar <$fd>)) {
8002 chomp $line;
8003 $linenr++;
8005 print qq!<tr id="l$linenr" class="$color_class">!.
8006 qq!<td class="sha1"><a href=""> </a></td>!.
8007 qq!<td class="extra_column" nowrap="nowrap"></td>!.
8008 qq!<td class="extra_column" nowrap="nowrap"></td>!.
8009 qq!<td class="linenr">!.
8010 qq!<a class="linenr" href="">$linenr</a></td>!;
8011 print qq!<td class="pre">! . esc_html($line) . "</td>\n";
8012 print qq!</tr>\n!;
8015 } else { # porcelain, i.e. ordinary blame
8016 my %metainfo = (); # saves information about commits
8018 # blame data
8019 LINE:
8020 while (my $line = to_utf8(scalar <$fd>)) {
8021 chomp $line;
8022 # the header: <SHA-1> <src lineno> <dst lineno> [<lines in group>]
8023 # no <lines in group> for subsequent lines in group of lines
8024 my ($full_rev, $orig_lineno, $lineno, $group_size) =
8025 ($line =~ /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/);
8026 if (!exists $metainfo{$full_rev}) {
8027 $metainfo{$full_rev} = { 'nprevious' => 0 };
8029 my $meta = $metainfo{$full_rev};
8030 my $data;
8031 while ($data = to_utf8(scalar <$fd>)) {
8032 chomp $data;
8033 last if ($data =~ s/^\t//); # contents of line
8034 if ($data =~ /^(\S+)(?: (.*))?$/) {
8035 $meta->{$1} = $2 unless exists $meta->{$1};
8037 if ($data =~ /^previous /) {
8038 $meta->{'nprevious'}++;
8041 my $short_rev = substr($full_rev, 0, 8);
8042 my $author = $meta->{'author'};
8043 my %date =
8044 parse_date($meta->{'author-time'}, $meta->{'author-tz'});
8045 my $date = $date{'iso-tz'};
8046 if ($group_size) {
8047 $current_color = ($current_color + 1) % $num_colors;
8049 my $tr_class = $rev_color[$current_color];
8050 $tr_class .= ' boundary' if (exists $meta->{'boundary'});
8051 $tr_class .= ' no-previous' if ($meta->{'nprevious'} == 0);
8052 $tr_class .= ' multiple-previous' if ($meta->{'nprevious'} > 1);
8053 print "<tr id=\"l$lineno\" class=\"$tr_class\">\n";
8054 if ($group_size) {
8055 my $rowspan = $group_size > 1 ? " rowspan=\"$group_size\"" : "";
8056 print "<td class=\"sha1\"";
8057 print " title=\"". esc_html($author) . ", $date\"";
8058 print "$rowspan>";
8059 print $cgi->a({-href => href(action=>"commit",
8060 hash=>$full_rev,
8061 file_name=>$file_name)},
8062 esc_html($short_rev));
8063 if ($group_size >= 2) {
8064 my @author_initials = ($author =~ /\b([[:upper:]])\B/g);
8065 if (@author_initials) {
8066 print "<br />" .
8067 esc_html(join('', @author_initials));
8068 # or join('.', ...)
8071 print "</td>\n";
8072 print "<td class=\"extra_column\" nowrap=\"nowrap\"$rowspan>". esc_html($author) . "</td>";
8073 print "<td class=\"extra_column\" nowrap=\"nowrap\"$rowspan>". $date . "</td>";
8075 # 'previous' <sha1 of parent commit> <filename at commit>
8076 if (exists $meta->{'previous'} &&
8077 $meta->{'previous'} =~ /^([a-fA-F0-9]{40}) (.*)$/) {
8078 $meta->{'parent'} = $1;
8079 $meta->{'file_parent'} = unquote($2);
8081 my $linenr_commit =
8082 exists($meta->{'parent'}) ?
8083 $meta->{'parent'} : $full_rev;
8084 my $linenr_filename =
8085 exists($meta->{'file_parent'}) ?
8086 $meta->{'file_parent'} : unquote($meta->{'filename'});
8087 my $blamed = href(action => 'blame',
8088 file_name => $linenr_filename,
8089 hash_base => $linenr_commit);
8090 print "<td class=\"linenr\">";
8091 print $cgi->a({ -href => "$blamed#l$orig_lineno",
8092 -class => "linenr" },
8093 esc_html($lineno));
8094 print "</td>";
8095 print "<td class=\"pre\">" . esc_html($data) . "</td>\n";
8096 print "</tr>\n";
8097 } # end while
8101 # footer
8102 print "</tbody>\n".
8103 "</table>\n"; # class="blame"
8104 print "</div>\n"; # class="blame_body"
8105 close $fd
8106 or print "Reading blob failed\n";
8108 git_footer_html();
8111 sub git_blame {
8112 git_blame_common();
8115 sub git_blame_incremental {
8116 git_blame_common('incremental');
8119 sub git_blame_data {
8120 git_blame_common('data');
8123 sub git_tags {
8124 my $head = git_get_head_hash($project);
8125 git_header_html();
8126 git_print_page_nav('','', $head,undef,$head,format_ref_views('tags'));
8127 git_print_header_div('summary', $project);
8129 my @tagslist = git_get_tags_list();
8130 if (@tagslist) {
8131 git_tags_body(\@tagslist);
8133 git_footer_html();
8136 sub git_refs {
8137 my $order = $input_params{'order'};
8138 if (defined $order && $order !~ m/age|name/) {
8139 die_error(400, "Unknown order parameter");
8142 my $head = git_get_head_hash($project);
8143 git_header_html();
8144 git_print_page_nav('','', $head,undef,$head,format_ref_views('refs'));
8145 git_print_header_div('summary', $project);
8147 my @refslist = git_get_tags_list(undef, 1, $order);
8148 if (@refslist) {
8149 git_tags_body(\@refslist, undef, undef, undef, $head, 1, $order);
8151 git_footer_html();
8154 sub git_heads {
8155 my $head = git_get_head_hash($project);
8156 git_header_html();
8157 git_print_page_nav('','', $head,undef,$head,format_ref_views('heads'));
8158 git_print_header_div('summary', $project);
8160 my @headslist = git_get_heads_list();
8161 if (@headslist) {
8162 git_heads_body(\@headslist, $head);
8164 git_footer_html();
8167 # used both for single remote view and for list of all the remotes
8168 sub git_remotes {
8169 gitweb_check_feature('remote_heads')
8170 or die_error(403, "Remote heads view is disabled");
8172 my $head = git_get_head_hash($project);
8173 my $remote = $input_params{'hash'};
8175 my $remotedata = git_get_remotes_list($remote);
8176 die_error(500, "Unable to get remote information") unless defined $remotedata;
8178 unless (%$remotedata) {
8179 die_error(404, defined $remote ?
8180 "Remote $remote not found" :
8181 "No remotes found");
8184 git_header_html(undef, undef, -action_extra => $remote);
8185 git_print_page_nav('', '', $head, undef, $head,
8186 format_ref_views($remote ? '' : 'remotes'));
8188 fill_remote_heads($remotedata);
8189 if (defined $remote) {
8190 git_print_header_div('remotes', "$remote remote for $project");
8191 git_remote_block($remote, $remotedata->{$remote}, undef, $head);
8192 } else {
8193 git_print_header_div('summary', "$project remotes");
8194 git_remotes_body($remotedata, undef, $head);
8197 git_footer_html();
8200 sub git_blob_plain {
8201 my $type = shift;
8202 my $expires;
8204 if (!defined $hash) {
8205 if (defined $file_name) {
8206 my $base = $hash_base || git_get_head_hash($project);
8207 $hash = git_get_hash_by_path($base, $file_name, "blob")
8208 or die_error(404, "Cannot find file");
8209 } else {
8210 die_error(400, "No file name defined");
8212 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
8213 # blobs defined by non-textual hash id's can be cached
8214 $expires = "+1d";
8217 defined(my $fd = git_cmd_pipe "cat-file", "blob", $hash)
8218 or die_error(500, "Open git-cat-file blob '$hash' failed");
8219 binmode($fd);
8221 # content-type (can include charset)
8222 my $leader;
8223 ($type, $leader) = blob_contenttype($fd, $file_name, $type);
8225 # "save as" filename, even when no $file_name is given
8226 my $save_as = "$hash";
8227 if (defined $file_name) {
8228 $save_as = $file_name;
8229 } elsif ($type =~ m/^text\//) {
8230 $save_as .= '.txt';
8233 # With XSS prevention on, blobs of all types except a few known safe
8234 # ones are served with "Content-Disposition: attachment" to make sure
8235 # they don't run in our security domain. For certain image types,
8236 # blob view writes an <img> tag referring to blob_plain view, and we
8237 # want to be sure not to break that by serving the image as an
8238 # attachment (though Firefox 3 doesn't seem to care).
8239 my $sandbox = $prevent_xss &&
8240 $type !~ m!^(?:text/[a-z]+|image/(?:gif|png|jpeg))(?:[ ;]|$)!;
8242 # serve text/* as text/plain
8243 if ($prevent_xss &&
8244 ($type =~ m!^text/[a-z]+\b(.*)$! ||
8245 ($type =~ m!^[a-z]+/[a-z]\+xml\b(.*)$! && -T $fd))) {
8246 my $rest = $1;
8247 $rest = defined $rest ? $rest : '';
8248 $type = "text/plain$rest";
8251 print $cgi->header(
8252 -type => $type,
8253 -expires => $expires,
8254 -content_disposition =>
8255 ($sandbox ? 'attachment' : 'inline')
8256 . '; filename="' . $save_as . '"');
8257 binmode STDOUT, ':raw';
8258 $fcgi_raw_mode = 1;
8259 print $leader if defined $leader;
8260 my $buf;
8261 while (read($fd, $buf, 32768)) {
8262 print $buf;
8264 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
8265 $fcgi_raw_mode = 0;
8266 close $fd;
8269 sub git_blob {
8270 my $expires;
8272 my $fullhash;
8273 if (!defined $hash) {
8274 if (defined $file_name) {
8275 my $base = $hash_base || git_get_head_hash($project);
8276 $hash = git_get_hash_by_path($base, $file_name, "blob")
8277 or die_error(404, "Cannot find file");
8278 $fullhash = $hash;
8279 } else {
8280 die_error(400, "No file name defined");
8282 } elsif ($hash =~ m/^[0-9a-fA-F]{40}$/) {
8283 # blobs defined by non-textual hash id's can be cached
8284 $expires = "+1d";
8285 $fullhash = $hash;
8287 $fullhash = git_get_full_hash($project, $hash) unless $fullhash;
8289 my $have_blame = gitweb_check_feature('blame');
8290 defined(my $fd = git_cmd_pipe "cat-file", "blob", $hash)
8291 or die_error(500, "Couldn't cat $file_name, $hash");
8292 binmode($fd);
8293 my $mimetype = blob_mimetype($fd, $file_name);
8294 # use 'blob_plain' (aka 'raw') view for files that cannot be displayed
8295 if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
8296 close $fd;
8297 return git_blob_plain($mimetype);
8299 # we can have blame only for text/* mimetype
8300 $have_blame &&= ($mimetype =~ m!^text/!);
8302 my $highlight = gitweb_check_feature('highlight') && defined $highlight_bin;
8303 my $syntax = guess_file_syntax($fd, $mimetype, $file_name) if $highlight;
8304 my $highlight_mode_active;
8305 ($fd, $highlight_mode_active) = run_highlighter($fd, $syntax) if $syntax;
8307 git_header_html(undef, $expires);
8308 my $formats_nav = '';
8309 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
8310 if (defined $file_name) {
8311 if ($have_blame) {
8312 $formats_nav .=
8313 $cgi->a({-href => href(action=>"blame", -replay=>1),
8314 -class => "blamelink"},
8315 "blame") .
8316 " | ";
8318 $formats_nav .=
8319 $cgi->a({-href => href(action=>"history", -replay=>1)},
8320 "history") .
8321 " | " .
8322 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
8323 "raw") .
8324 " | " .
8325 $cgi->a({-href => href(action=>"blob",
8326 hash_base=>"HEAD", file_name=>$file_name)},
8327 "HEAD");
8328 } else {
8329 $formats_nav .=
8330 $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
8331 "raw");
8333 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
8334 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
8335 } else {
8336 print "<div class=\"page_nav\">\n" .
8337 "<br/><br/></div>\n" .
8338 "<div class=\"title\">".esc_html($hash)."</div>\n";
8340 git_print_page_path($file_name, "blob", $hash_base);
8341 print "<div class=\"title_text\">\n" .
8342 "<table class=\"object_header\">\n";
8343 print "<tr><td>blob</td><td class=\"sha1\">$fullhash</td></tr>\n";
8344 print "</table>".
8345 "</div>\n";
8346 print "<div class=\"page_body\">\n";
8347 if ($mimetype =~ m!^image/!) {
8348 print qq!<img class="blob" type="!.esc_attr($mimetype).qq!"!;
8349 if ($file_name) {
8350 print qq! alt="!.esc_attr($file_name).qq!" title="!.esc_attr($file_name).qq!"!;
8352 print qq! src="! .
8353 href(action=>"blob_plain", hash=>$hash,
8354 hash_base=>$hash_base, file_name=>$file_name) .
8355 qq!" />\n!;
8356 } else {
8357 my $nr;
8358 while (my $line = to_utf8(scalar <$fd>)) {
8359 chomp $line;
8360 $nr++;
8361 $line = untabify($line);
8362 printf qq!<div class="pre"><a id="l%i" href="%s#l%i" class="linenr">%4i</a> %s</div>\n!,
8363 $nr, esc_attr(href(-replay => 1)), $nr, $nr,
8364 $highlight_mode_active ? sanitize($line) : esc_html($line, -nbsp=>1);
8367 close $fd
8368 or print "Reading blob failed.\n";
8369 print "</div>";
8370 git_footer_html();
8373 sub git_tree {
8374 my $fullhash;
8375 if (!defined $hash_base) {
8376 $hash_base = "HEAD";
8378 if (!defined $hash) {
8379 if (defined $file_name) {
8380 $hash = git_get_hash_by_path($hash_base, $file_name, "tree");
8381 $fullhash = $hash;
8382 } else {
8383 $hash = $hash_base;
8386 die_error(404, "No such tree") unless defined($hash);
8387 $fullhash = $hash if !$fullhash && $hash =~ m/^[0-9a-fA-F]{40}$/;
8388 $fullhash = git_get_full_hash($project, $hash) unless $fullhash;
8390 my $show_sizes = gitweb_check_feature('show-sizes');
8391 my $have_blame = gitweb_check_feature('blame');
8393 my @entries = ();
8395 local $/ = "\0";
8396 defined(my $fd = git_cmd_pipe "ls-tree", '-z',
8397 ($show_sizes ? '-l' : ()), @extra_options, $hash)
8398 or die_error(500, "Open git-ls-tree failed");
8399 @entries = map { chomp; to_utf8($_) } <$fd>;
8400 close $fd
8401 or die_error(404, "Reading tree failed");
8404 git_header_html();
8405 my $basedir = '';
8406 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
8407 my $refs = git_get_references();
8408 my $ref = format_ref_marker($refs, $co{'id'});
8409 my @views_nav = ();
8410 if (defined $file_name) {
8411 push @views_nav,
8412 $cgi->a({-href => href(action=>"history", -replay=>1)},
8413 "history"),
8414 $cgi->a({-href => href(action=>"tree",
8415 hash_base=>"HEAD", file_name=>$file_name)},
8416 "HEAD"),
8418 my $snapshot_links = format_snapshot_links($hash);
8419 if (defined $snapshot_links) {
8420 # FIXME: Should be available when we have no hash base as well.
8421 push @views_nav, $snapshot_links;
8423 git_print_page_nav('tree','', $hash_base, undef, undef,
8424 join(' | ', @views_nav));
8425 git_print_header_div('commit', esc_html($co{'title'}), $hash_base, undef, $ref);
8426 } else {
8427 undef $hash_base;
8428 print "<div class=\"page_nav\">\n";
8429 print "<br/><br/></div>\n";
8430 print "<div class=\"title\">".esc_html($hash)."</div>\n";
8432 if (defined $file_name) {
8433 $basedir = $file_name;
8434 if ($basedir ne '' && substr($basedir, -1) ne '/') {
8435 $basedir .= '/';
8437 git_print_page_path($file_name, 'tree', $hash_base);
8439 print "<div class=\"title_text\">\n" .
8440 "<table class=\"object_header\">\n";
8441 print "<tr><td>tree</td><td class=\"sha1\">$fullhash</td></tr>\n";
8442 print "</table>".
8443 "</div>\n";
8444 print "<div class=\"page_body\">\n";
8445 print "<table class=\"tree\">\n";
8446 my $alternate = 1;
8447 # '..' (top directory) link if possible
8448 if (defined $hash_base &&
8449 defined $file_name && $file_name =~ m![^/]+$!) {
8450 if ($alternate) {
8451 print "<tr class=\"dark\">\n";
8452 } else {
8453 print "<tr class=\"light\">\n";
8455 $alternate ^= 1;
8457 my $up = $file_name;
8458 $up =~ s!/?[^/]+$!!;
8459 undef $up unless $up;
8460 # based on git_print_tree_entry
8461 print '<td class="mode">' . mode_str('040000') . "</td>\n";
8462 print '<td class="size">&#160;</td>'."\n" if $show_sizes;
8463 print '<td class="list">';
8464 print $cgi->a({-href => href(action=>"tree",
8465 hash_base=>$hash_base,
8466 file_name=>$up)},
8467 "..");
8468 print "</td>\n";
8469 print "<td class=\"link\"></td>\n";
8471 print "</tr>\n";
8473 foreach my $line (@entries) {
8474 my %t = parse_ls_tree_line($line, -z => 1, -l => $show_sizes);
8476 if ($alternate) {
8477 print "<tr class=\"dark\">\n";
8478 } else {
8479 print "<tr class=\"light\">\n";
8481 $alternate ^= 1;
8483 git_print_tree_entry(\%t, $basedir, $hash_base, $have_blame);
8485 print "</tr>\n";
8487 print "</table>\n" .
8488 "</div>";
8489 git_footer_html();
8492 sub sanitize_for_filename {
8493 my $name = shift;
8495 $name =~ s!/!-!g;
8496 $name =~ s/[^[:alnum:]_.-]//g;
8498 return $name;
8501 sub snapshot_name {
8502 my ($project, $hash) = @_;
8504 # path/to/project.git -> project
8505 # path/to/project/.git -> project
8506 my $name = to_utf8($project);
8507 $name =~ s,([^/])/*\.git$,$1,;
8508 $name = sanitize_for_filename(basename($name));
8510 my $ver = $hash;
8511 if ($hash =~ /^[0-9a-fA-F]+$/) {
8512 # shorten SHA-1 hash
8513 my $full_hash = git_get_full_hash($project, $hash);
8514 if ($full_hash =~ /^$hash/ && length($hash) > 7) {
8515 $ver = git_get_short_hash($project, $hash);
8517 } elsif ($hash =~ m!^refs/tags/(.*)$!) {
8518 # tags don't need shortened SHA-1 hash
8519 $ver = $1;
8520 } else {
8521 # branches and other need shortened SHA-1 hash
8522 my $strip_refs = join '|', map { quotemeta } get_branch_refs();
8523 if ($hash =~ m!^refs/($strip_refs|remotes)/(.*)$!) {
8524 my $ref_dir = (defined $1) ? $1 : '';
8525 $ver = $2;
8527 $ref_dir = sanitize_for_filename($ref_dir);
8528 # for refs neither in heads nor remotes we want to
8529 # add a ref dir to archive name
8530 if ($ref_dir ne '' and $ref_dir ne 'heads' and $ref_dir ne 'remotes') {
8531 $ver = $ref_dir . '-' . $ver;
8534 $ver .= '-' . git_get_short_hash($project, $hash);
8536 # special case of sanitization for filename - we change
8537 # slashes to dots instead of dashes
8538 # in case of hierarchical branch names
8539 $ver =~ s!/!.!g;
8540 $ver =~ s/[^[:alnum:]_.-]//g;
8542 # name = project-version_string
8543 $name = "$name-$ver";
8545 return wantarray ? ($name, $name) : $name;
8548 sub exit_if_unmodified_since {
8549 my ($latest_epoch) = @_;
8550 our $cgi;
8552 my $if_modified = $cgi->http('IF_MODIFIED_SINCE');
8553 if (defined $if_modified) {
8554 my $since;
8555 if (eval { require HTTP::Date; 1; }) {
8556 $since = HTTP::Date::str2time($if_modified);
8557 } elsif (eval { require Time::ParseDate; 1; }) {
8558 $since = Time::ParseDate::parsedate($if_modified, GMT => 1);
8560 if (defined $since && $latest_epoch <= $since) {
8561 my %latest_date = parse_date($latest_epoch);
8562 print $cgi->header(
8563 -last_modified => $latest_date{'rfc2822'},
8564 -status => '304 Not Modified');
8565 goto DONE_GITWEB;
8570 sub git_snapshot {
8571 my $format = $input_params{'snapshot_format'};
8572 if (!@snapshot_fmts) {
8573 die_error(403, "Snapshots not allowed");
8575 # default to first supported snapshot format
8576 $format ||= $snapshot_fmts[0];
8577 if ($format !~ m/^[a-z0-9]+$/) {
8578 die_error(400, "Invalid snapshot format parameter");
8579 } elsif (!exists($known_snapshot_formats{$format})) {
8580 die_error(400, "Unknown snapshot format");
8581 } elsif ($known_snapshot_formats{$format}{'disabled'}) {
8582 die_error(403, "Snapshot format not allowed");
8583 } elsif (!grep($_ eq $format, @snapshot_fmts)) {
8584 die_error(403, "Unsupported snapshot format");
8587 my $type = git_get_type("$hash^{}");
8588 if (!$type) {
8589 die_error(404, 'Object does not exist');
8590 } elsif ($type eq 'blob') {
8591 die_error(400, 'Object is not a tree-ish');
8594 my ($name, $prefix) = snapshot_name($project, $hash);
8595 my $filename = "$name$known_snapshot_formats{$format}{'suffix'}";
8597 my %co = parse_commit($hash);
8598 exit_if_unmodified_since($co{'committer_epoch'}) if %co;
8600 my @cmd = (
8601 git_cmd(), 'archive',
8602 "--format=$known_snapshot_formats{$format}{'format'}",
8603 "--prefix=$prefix/", $hash);
8604 if (exists $known_snapshot_formats{$format}{'compressor'}) {
8605 @cmd = ($posix_shell_bin, '-c', quote_command(@cmd) .
8606 ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}}));
8609 $filename =~ s/(["\\])/\\$1/g;
8610 my %latest_date;
8611 if (%co) {
8612 %latest_date = parse_date($co{'committer_epoch'}, $co{'committer_tz'});
8615 print $cgi->header(
8616 -type => $known_snapshot_formats{$format}{'type'},
8617 -content_disposition => 'inline; filename="' . $filename . '"',
8618 %co ? (-last_modified => $latest_date{'rfc2822'}) : (),
8619 -status => '200 OK');
8621 defined(my $fd = cmd_pipe @cmd)
8622 or die_error(500, "Execute git-archive failed");
8623 binmode($fd);
8624 binmode STDOUT, ':raw';
8625 $fcgi_raw_mode = 1;
8626 my $buf;
8627 while (read($fd, $buf, 32768)) {
8628 print $buf;
8630 binmode STDOUT, ':utf8'; # as set at the beginning of gitweb.cgi
8631 $fcgi_raw_mode = 0;
8632 close $fd;
8635 sub git_log_generic {
8636 my ($fmt_name, $body_subr, $base, $parent, $file_name, $file_hash) = @_;
8638 my $head = git_get_head_hash($project);
8639 if (!defined $base) {
8640 $base = $head;
8642 if (!defined $page) {
8643 $page = 0;
8645 my $refs = git_get_references();
8647 my $commit_hash = $base;
8648 if (defined $parent) {
8649 $commit_hash = "$parent..$base";
8651 my @commitlist =
8652 parse_commits($commit_hash, 101, (100 * $page),
8653 defined $file_name ? ($file_name, "--full-history") : ());
8655 my $ftype;
8656 if (!defined $file_hash && defined $file_name) {
8657 # some commits could have deleted file in question,
8658 # and not have it in tree, but one of them has to have it
8659 for (my $i = 0; $i < @commitlist; $i++) {
8660 $file_hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
8661 last if defined $file_hash;
8664 if (defined $file_hash) {
8665 $ftype = git_get_type($file_hash);
8667 if (defined $file_name && !defined $ftype) {
8668 die_error(500, "Unknown type of object");
8670 my %co;
8671 if (defined $file_name) {
8672 %co = parse_commit($base)
8673 or die_error(404, "Unknown commit object");
8677 my $paging_nav = format_log_nav($fmt_name, $page, $#commitlist >= 100);
8678 my $next_link = '';
8679 if ($#commitlist >= 100) {
8680 $next_link =
8681 $cgi->a({-href => href(-replay=>1, page=>$page+1),
8682 -accesskey => "n", -title => "Alt-n"}, "next");
8684 my ($patch_max) = gitweb_get_feature('patches');
8685 if ($patch_max && !defined $file_name) {
8686 if ($patch_max < 0 || @commitlist <= $patch_max) {
8687 $paging_nav .= " &#183; " .
8688 $cgi->a({-href => href(action=>"patches", -replay=>1)},
8689 "patches");
8694 local $action = 'fulllog';
8695 git_header_html();
8697 git_print_page_nav($fmt_name,'', $hash,$hash,$hash, $paging_nav);
8698 if (defined $file_name) {
8699 git_print_header_div('commit', esc_html($co{'title'}), $base);
8700 } else {
8701 git_print_header_div('summary', $project)
8703 git_print_page_path($file_name, $ftype, $hash_base)
8704 if (defined $file_name);
8706 $body_subr->(\@commitlist, 0, 99, $refs, $next_link,
8707 $file_name, $file_hash, $ftype);
8709 git_footer_html();
8712 sub git_log {
8713 git_log_generic('log', \&git_log_body,
8714 $hash, $hash_parent);
8717 sub git_commit {
8718 $hash ||= $hash_base || "HEAD";
8719 my %co = parse_commit($hash)
8720 or die_error(404, "Unknown commit object");
8722 my $parent = $co{'parent'};
8723 my $parents = $co{'parents'}; # listref
8725 # we need to prepare $formats_nav before any parameter munging
8726 my $formats_nav;
8727 if (!defined $parent) {
8728 # --root commitdiff
8729 $formats_nav .= '(initial)';
8730 } elsif (@$parents == 1) {
8731 # single parent commit
8732 $formats_nav .=
8733 '(parent: ' .
8734 $cgi->a({-href => href(action=>"commit",
8735 hash=>$parent)},
8736 esc_html(substr($parent, 0, 7))) .
8737 ')';
8738 } else {
8739 # merge commit
8740 $formats_nav .=
8741 '(merge: ' .
8742 join(' ', map {
8743 $cgi->a({-href => href(action=>"commit",
8744 hash=>$_)},
8745 esc_html(substr($_, 0, 7)));
8746 } @$parents ) .
8747 ')';
8749 if (gitweb_check_feature('patches') && @$parents <= 1) {
8750 $formats_nav .= " | " .
8751 $cgi->a({-href => href(action=>"patch", -replay=>1)},
8752 "patch");
8755 if (!defined $parent) {
8756 $parent = "--root";
8758 my @difftree;
8759 defined(my $fd = git_cmd_pipe "diff-tree", '-r', "--no-commit-id",
8760 @diff_opts,
8761 (@$parents <= 1 ? $parent : '-c'),
8762 $hash, "--")
8763 or die_error(500, "Open git-diff-tree failed");
8764 @difftree = map { chomp; to_utf8($_) } <$fd>;
8765 close $fd or die_error(404, "Reading git-diff-tree failed");
8767 # non-textual hash id's can be cached
8768 my $expires;
8769 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
8770 $expires = "+1d";
8772 my $refs = git_get_references();
8773 my $ref = format_ref_marker($refs, $co{'id'});
8775 git_header_html(undef, $expires);
8776 git_print_page_nav('commit', '',
8777 $hash, $co{'tree'}, $hash,
8778 $formats_nav);
8780 if (defined $co{'parent'}) {
8781 git_print_header_div('commitdiff', esc_html($co{'title'}), $hash, undef, $ref);
8782 } else {
8783 git_print_header_div('tree', esc_html($co{'title'}), $co{'tree'}, $hash, $ref);
8785 print "<div class=\"title_text\">\n" .
8786 "<table class=\"object_header\">\n";
8787 print "<tr><td>commit</td><td class=\"sha1\">$co{'id'}</td></tr>\n";
8788 git_print_authorship_rows(\%co);
8789 print "<tr>" .
8790 "<td>tree</td>" .
8791 "<td class=\"sha1\">" .
8792 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash),
8793 class => "list"}, $co{'tree'}) .
8794 "</td>" .
8795 "<td class=\"link\">" .
8796 $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$hash)},
8797 "tree");
8798 my $snapshot_links = format_snapshot_links($hash);
8799 if (defined $snapshot_links) {
8800 print " | " . $snapshot_links;
8802 print "</td>" .
8803 "</tr>\n";
8805 foreach my $par (@$parents) {
8806 print "<tr>" .
8807 "<td>parent</td>" .
8808 "<td class=\"sha1\">" .
8809 $cgi->a({-href => href(action=>"commit", hash=>$par),
8810 class => "list"}, $par) .
8811 "</td>" .
8812 "<td class=\"link\">" .
8813 $cgi->a({-href => href(action=>"commit", hash=>$par)}, "commit") .
8814 " | " .
8815 $cgi->a({-href => href(action=>"commitdiff", hash=>$hash, hash_parent=>$par)}, "diff") .
8816 "</td>" .
8817 "</tr>\n";
8819 print "</table>".
8820 "</div>\n";
8822 print "<div class=\"page_body\">\n";
8823 git_print_log($co{'comment'});
8824 print "</div>\n";
8826 git_difftree_body(\@difftree, $hash, @$parents);
8828 git_footer_html();
8831 sub git_object {
8832 # object is defined by:
8833 # - hash or hash_base alone
8834 # - hash_base and file_name
8835 my $type;
8837 # - hash or hash_base alone
8838 if ($hash || ($hash_base && !defined $file_name)) {
8839 my $object_id = $hash || $hash_base;
8841 defined(my $fd = git_cmd_pipe 'cat-file', '-t', $object_id)
8842 or die_error(404, "Object does not exist");
8843 $type = <$fd>;
8844 chomp $type;
8845 close $fd
8846 or die_error(404, "Object does not exist");
8848 # - hash_base and file_name
8849 } elsif ($hash_base && defined $file_name) {
8850 $file_name =~ s,/+$,,;
8852 system(git_cmd(), "cat-file", '-e', $hash_base) == 0
8853 or die_error(404, "Base object does not exist");
8855 # here errors should not happen
8856 defined(my $fd = git_cmd_pipe "ls-tree", $hash_base, "--", $file_name)
8857 or die_error(500, "Open git-ls-tree failed");
8858 my $line = to_utf8(scalar <$fd>);
8859 close $fd;
8861 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
8862 unless ($line && $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/) {
8863 die_error(404, "File or directory for given base does not exist");
8865 $type = $2;
8866 $hash = $3;
8867 } else {
8868 die_error(400, "Not enough information to find object");
8871 print $cgi->redirect(-uri => href(action=>$type, -full=>1,
8872 hash=>$hash, hash_base=>$hash_base,
8873 file_name=>$file_name),
8874 -status => '302 Found');
8877 sub git_blobdiff {
8878 my $format = shift || 'html';
8879 my $diff_style = $input_params{'diff_style'} || 'inline';
8881 my $fd;
8882 my @difftree;
8883 my %diffinfo;
8884 my $expires;
8886 # preparing $fd and %diffinfo for git_patchset_body
8887 # new style URI
8888 if (defined $hash_base && defined $hash_parent_base) {
8889 if (defined $file_name) {
8890 # read raw output
8891 defined($fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
8892 $hash_parent_base, $hash_base,
8893 "--", (defined $file_parent ? $file_parent : ()), $file_name)
8894 or die_error(500, "Open git-diff-tree failed");
8895 @difftree = map { chomp; to_utf8($_) } <$fd>;
8896 close $fd
8897 or die_error(404, "Reading git-diff-tree failed");
8898 @difftree
8899 or die_error(404, "Blob diff not found");
8901 } elsif (defined $hash &&
8902 $hash =~ /[0-9a-fA-F]{40}/) {
8903 # try to find filename from $hash
8905 # read filtered raw output
8906 defined($fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
8907 $hash_parent_base, $hash_base, "--")
8908 or die_error(500, "Open git-diff-tree failed");
8909 @difftree =
8910 # ':100644 100644 03b21826... 3b93d5e7... M ls-files.c'
8911 # $hash == to_id
8912 grep { /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} $hash/ }
8913 map { chomp; to_utf8($_) } <$fd>;
8914 close $fd
8915 or die_error(404, "Reading git-diff-tree failed");
8916 @difftree
8917 or die_error(404, "Blob diff not found");
8919 } else {
8920 die_error(400, "Missing one of the blob diff parameters");
8923 if (@difftree > 1) {
8924 die_error(400, "Ambiguous blob diff specification");
8927 %diffinfo = parse_difftree_raw_line($difftree[0]);
8928 $file_parent ||= $diffinfo{'from_file'} || $file_name;
8929 $file_name ||= $diffinfo{'to_file'};
8931 $hash_parent ||= $diffinfo{'from_id'};
8932 $hash ||= $diffinfo{'to_id'};
8934 # non-textual hash id's can be cached
8935 if ($hash_base =~ m/^[0-9a-fA-F]{40}$/ &&
8936 $hash_parent_base =~ m/^[0-9a-fA-F]{40}$/) {
8937 $expires = '+1d';
8940 # open patch output
8941 defined($fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
8942 '-p', ($format eq 'html' ? "--full-index" : ()),
8943 $hash_parent_base, $hash_base,
8944 "--", (defined $file_parent ? $file_parent : ()), $file_name)
8945 or die_error(500, "Open git-diff-tree failed");
8948 # old/legacy style URI -- not generated anymore since 1.4.3.
8949 if (!%diffinfo) {
8950 die_error('404 Not Found', "Missing one of the blob diff parameters")
8953 # header
8954 if ($format eq 'html') {
8955 my $formats_nav =
8956 $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
8957 "raw");
8958 $formats_nav .= diff_style_nav($diff_style);
8959 git_header_html(undef, $expires);
8960 if (defined $hash_base && (my %co = parse_commit($hash_base))) {
8961 git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
8962 git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
8963 } else {
8964 print "<div class=\"page_nav\"><br/>$formats_nav<br/></div>\n";
8965 print "<div class=\"title\">".esc_html("$hash vs $hash_parent")."</div>\n";
8967 if (defined $file_name) {
8968 git_print_page_path($file_name, "blob", $hash_base);
8969 } else {
8970 print "<div class=\"page_path\"></div>\n";
8973 } elsif ($format eq 'plain') {
8974 print $cgi->header(
8975 -type => 'text/plain',
8976 -charset => 'utf-8',
8977 -expires => $expires,
8978 -content_disposition => 'inline; filename="' . "$file_name" . '.patch"');
8980 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
8982 } else {
8983 die_error(400, "Unknown blobdiff format");
8986 # patch
8987 if ($format eq 'html') {
8988 print "<div class=\"page_body\">\n";
8990 git_patchset_body($fd, $diff_style,
8991 [ \%diffinfo ], $hash_base, $hash_parent_base);
8992 close $fd;
8994 print "</div>\n"; # class="page_body"
8995 git_footer_html();
8997 } else {
8998 while (my $line = to_utf8(scalar <$fd>)) {
8999 $line =~ s!a/($hash|$hash_parent)!'a/'.esc_path($diffinfo{'from_file'})!eg;
9000 $line =~ s!b/($hash|$hash_parent)!'b/'.esc_path($diffinfo{'to_file'})!eg;
9002 print $line;
9004 last if $line =~ m!^\+\+\+!;
9006 while (<$fd>) {
9007 print to_utf8($_);
9009 close $fd;
9013 sub git_blobdiff_plain {
9014 git_blobdiff('plain');
9017 # assumes that it is added as later part of already existing navigation,
9018 # so it returns "| foo | bar" rather than just "foo | bar"
9019 sub diff_style_nav {
9020 my ($diff_style, $is_combined) = @_;
9021 $diff_style ||= 'inline';
9023 return "" if ($is_combined);
9025 my @styles = (inline => 'inline', 'sidebyside' => 'side by side');
9026 my %styles = @styles;
9027 @styles =
9028 @styles[ map { $_ * 2 } 0..$#styles/2 ];
9030 return join '',
9031 map { " | ".$_ }
9032 map {
9033 $_ eq $diff_style ? $styles{$_} :
9034 $cgi->a({-href => href(-replay=>1, diff_style => $_)}, $styles{$_})
9035 } @styles;
9038 sub git_commitdiff {
9039 my %params = @_;
9040 my $format = $params{-format} || 'html';
9041 my $diff_style = $input_params{'diff_style'} || 'inline';
9043 my ($patch_max) = gitweb_get_feature('patches');
9044 if ($format eq 'patch') {
9045 die_error(403, "Patch view not allowed") unless $patch_max;
9048 $hash ||= $hash_base || "HEAD";
9049 my %co = parse_commit($hash)
9050 or die_error(404, "Unknown commit object");
9052 # choose format for commitdiff for merge
9053 if (! defined $hash_parent && @{$co{'parents'}} > 1) {
9054 $hash_parent = '--cc';
9056 # we need to prepare $formats_nav before almost any parameter munging
9057 my $formats_nav;
9058 if ($format eq 'html') {
9059 $formats_nav =
9060 $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
9061 "raw");
9062 if ($patch_max && @{$co{'parents'}} <= 1) {
9063 $formats_nav .= " | " .
9064 $cgi->a({-href => href(action=>"patch", -replay=>1)},
9065 "patch");
9067 $formats_nav .= diff_style_nav($diff_style, @{$co{'parents'}} > 1);
9069 if (defined $hash_parent &&
9070 $hash_parent ne '-c' && $hash_parent ne '--cc') {
9071 # commitdiff with two commits given
9072 my $hash_parent_short = $hash_parent;
9073 if ($hash_parent =~ m/^[0-9a-fA-F]{40}$/) {
9074 $hash_parent_short = substr($hash_parent, 0, 7);
9076 $formats_nav .=
9077 ' (from';
9078 for (my $i = 0; $i < @{$co{'parents'}}; $i++) {
9079 if ($co{'parents'}[$i] eq $hash_parent) {
9080 $formats_nav .= ' parent ' . ($i+1);
9081 last;
9084 $formats_nav .= ': ' .
9085 $cgi->a({-href => href(-replay=>1,
9086 hash=>$hash_parent, hash_base=>undef)},
9087 esc_html($hash_parent_short)) .
9088 ')';
9089 } elsif (!$co{'parent'}) {
9090 # --root commitdiff
9091 $formats_nav .= ' (initial)';
9092 } elsif (scalar @{$co{'parents'}} == 1) {
9093 # single parent commit
9094 $formats_nav .=
9095 ' (parent: ' .
9096 $cgi->a({-href => href(-replay=>1,
9097 hash=>$co{'parent'}, hash_base=>undef)},
9098 esc_html(substr($co{'parent'}, 0, 7))) .
9099 ')';
9100 } else {
9101 # merge commit
9102 if ($hash_parent eq '--cc') {
9103 $formats_nav .= ' | ' .
9104 $cgi->a({-href => href(-replay=>1,
9105 hash=>$hash, hash_parent=>'-c')},
9106 'combined');
9107 } else { # $hash_parent eq '-c'
9108 $formats_nav .= ' | ' .
9109 $cgi->a({-href => href(-replay=>1,
9110 hash=>$hash, hash_parent=>'--cc')},
9111 'compact');
9113 $formats_nav .=
9114 ' (merge: ' .
9115 join(' ', map {
9116 $cgi->a({-href => href(-replay=>1,
9117 hash=>$_, hash_base=>undef)},
9118 esc_html(substr($_, 0, 7)));
9119 } @{$co{'parents'}} ) .
9120 ')';
9124 my $hash_parent_param = $hash_parent;
9125 if (!defined $hash_parent_param) {
9126 # --cc for multiple parents, --root for parentless
9127 $hash_parent_param =
9128 @{$co{'parents'}} > 1 ? '--cc' : $co{'parent'} || '--root';
9131 # read commitdiff
9132 my $fd;
9133 my @difftree;
9134 if ($format eq 'html') {
9135 defined($fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
9136 "--no-commit-id", "--patch-with-raw", "--full-index",
9137 $hash_parent_param, $hash, "--")
9138 or die_error(500, "Open git-diff-tree failed");
9140 while (my $line = to_utf8(scalar <$fd>)) {
9141 chomp $line;
9142 # empty line ends raw part of diff-tree output
9143 last unless $line;
9144 push @difftree, scalar parse_difftree_raw_line($line);
9147 } elsif ($format eq 'plain') {
9148 defined($fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
9149 '-p', $hash_parent_param, $hash, "--")
9150 or die_error(500, "Open git-diff-tree failed");
9151 } elsif ($format eq 'patch') {
9152 # For commit ranges, we limit the output to the number of
9153 # patches specified in the 'patches' feature.
9154 # For single commits, we limit the output to a single patch,
9155 # diverging from the git-format-patch default.
9156 my @commit_spec = ();
9157 if ($hash_parent) {
9158 if ($patch_max > 0) {
9159 push @commit_spec, "-$patch_max";
9161 push @commit_spec, '-n', "$hash_parent..$hash";
9162 } else {
9163 if ($params{-single}) {
9164 push @commit_spec, '-1';
9165 } else {
9166 if ($patch_max > 0) {
9167 push @commit_spec, "-$patch_max";
9169 push @commit_spec, "-n";
9171 push @commit_spec, '--root', $hash;
9173 defined($fd = git_cmd_pipe "format-patch", @diff_opts,
9174 '--encoding=utf8', '--stdout', @commit_spec)
9175 or die_error(500, "Open git-format-patch failed");
9176 } else {
9177 die_error(400, "Unknown commitdiff format");
9180 # non-textual hash id's can be cached
9181 my $expires;
9182 if ($hash =~ m/^[0-9a-fA-F]{40}$/) {
9183 $expires = "+1d";
9186 # write commit message
9187 if ($format eq 'html') {
9188 my $refs = git_get_references();
9189 my $ref = format_ref_marker($refs, $co{'id'});
9191 git_header_html(undef, $expires);
9192 git_print_page_nav('commitdiff','', $hash,$co{'tree'},$hash, $formats_nav);
9193 git_print_header_div('commit', esc_html($co{'title'}), $hash, undef, $ref);
9194 print "<div class=\"title_text\">\n" .
9195 "<table class=\"object_header\">\n";
9196 git_print_authorship_rows(\%co);
9197 print "</table>".
9198 "</div>\n";
9199 print "<div class=\"page_body\">\n";
9200 if (@{$co{'comment'}} > 1) {
9201 print "<div class=\"log\">\n";
9202 git_print_log($co{'comment'}, -final_empty_line=> 1, -remove_title => 1);
9203 print "</div>\n"; # class="log"
9206 } elsif ($format eq 'plain') {
9207 my $refs = git_get_references("tags");
9208 my $tagname = git_get_rev_name_tags($hash);
9209 my $filename = basename($project) . "-$hash.patch";
9211 print $cgi->header(
9212 -type => 'text/plain',
9213 -charset => 'utf-8',
9214 -expires => $expires,
9215 -content_disposition => 'inline; filename="' . "$filename" . '"');
9216 my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
9217 print "From: " . to_utf8($co{'author'}) . "\n";
9218 print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
9219 print "Subject: " . to_utf8($co{'title'}) . "\n";
9221 print "X-Git-Tag: $tagname\n" if $tagname;
9222 print "X-Git-Url: " . $cgi->self_url() . "\n\n";
9224 foreach my $line (@{$co{'comment'}}) {
9225 print to_utf8($line) . "\n";
9227 print "---\n\n";
9228 } elsif ($format eq 'patch') {
9229 my $filename = basename($project) . "-$hash.patch";
9231 print $cgi->header(
9232 -type => 'text/plain',
9233 -charset => 'utf-8',
9234 -expires => $expires,
9235 -content_disposition => 'inline; filename="' . "$filename" . '"');
9238 # write patch
9239 if ($format eq 'html') {
9240 my $use_parents = !defined $hash_parent ||
9241 $hash_parent eq '-c' || $hash_parent eq '--cc';
9242 git_difftree_body(\@difftree, $hash,
9243 $use_parents ? @{$co{'parents'}} : $hash_parent);
9244 print "<br/>\n";
9246 git_patchset_body($fd, $diff_style,
9247 \@difftree, $hash,
9248 $use_parents ? @{$co{'parents'}} : $hash_parent);
9249 close $fd;
9250 print "</div>\n"; # class="page_body"
9251 git_footer_html();
9253 } elsif ($format eq 'plain') {
9254 while (<$fd>) {
9255 print to_utf8($_);
9257 close $fd
9258 or print "Reading git-diff-tree failed\n";
9259 } elsif ($format eq 'patch') {
9260 while (<$fd>) {
9261 print to_utf8($_);
9263 close $fd
9264 or print "Reading git-format-patch failed\n";
9268 sub git_commitdiff_plain {
9269 git_commitdiff(-format => 'plain');
9272 # format-patch-style patches
9273 sub git_patch {
9274 git_commitdiff(-format => 'patch', -single => 1);
9277 sub git_patches {
9278 git_commitdiff(-format => 'patch');
9281 sub git_history {
9282 git_log_generic('history', \&git_history_body,
9283 $hash_base, $hash_parent_base,
9284 $file_name, $hash);
9287 sub git_search {
9288 $searchtype ||= 'commit';
9290 # check if appropriate features are enabled
9291 gitweb_check_feature('search')
9292 or die_error(403, "Search is disabled");
9293 if ($searchtype eq 'pickaxe') {
9294 # pickaxe may take all resources of your box and run for several minutes
9295 # with every query - so decide by yourself how public you make this feature
9296 gitweb_check_feature('pickaxe')
9297 or die_error(403, "Pickaxe search is disabled");
9299 if ($searchtype eq 'grep') {
9300 # grep search might be potentially CPU-intensive, too
9301 gitweb_check_feature('grep')
9302 or die_error(403, "Grep search is disabled");
9305 if (!defined $searchtext) {
9306 die_error(400, "Text field is empty");
9308 if (!defined $hash) {
9309 $hash = git_get_head_hash($project);
9311 my %co = parse_commit($hash);
9312 if (!%co) {
9313 die_error(404, "Unknown commit object");
9315 if (!defined $page) {
9316 $page = 0;
9319 if ($searchtype eq 'commit' ||
9320 $searchtype eq 'author' ||
9321 $searchtype eq 'committer') {
9322 git_search_message(%co);
9323 } elsif ($searchtype eq 'pickaxe') {
9324 git_search_changes(%co);
9325 } elsif ($searchtype eq 'grep') {
9326 git_search_files(%co);
9327 } else {
9328 die_error(400, "Unknown search type");
9332 sub git_search_help {
9333 git_header_html();
9334 git_print_page_nav('','', $hash,$hash,$hash);
9335 print <<EOT;
9336 <p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
9337 regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
9338 the pattern entered is recognized as the POSIX extended
9339 <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
9340 insensitive).</p>
9341 <dl>
9342 <dt><b>commit</b></dt>
9343 <dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
9345 my $have_grep = gitweb_check_feature('grep');
9346 if ($have_grep) {
9347 print <<EOT;
9348 <dt><b>grep</b></dt>
9349 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
9350 a different one) are searched for the given pattern. On large trees, this search can take
9351 a while and put some strain on the server, so please use it with some consideration. Note that
9352 due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
9353 case-sensitive.</dd>
9356 print <<EOT;
9357 <dt><b>author</b></dt>
9358 <dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
9359 <dt><b>committer</b></dt>
9360 <dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
9362 my $have_pickaxe = gitweb_check_feature('pickaxe');
9363 if ($have_pickaxe) {
9364 print <<EOT;
9365 <dt><b>pickaxe</b></dt>
9366 <dd>All commits that caused the string to appear or disappear from any file (changes that
9367 added, removed or "modified" the string) will be listed. This search can take a while and
9368 takes a lot of strain on the server, so please use it wisely. Note that since you may be
9369 interested even in changes just changing the case as well, this search is case sensitive.</dd>
9372 print "</dl>\n";
9373 git_footer_html();
9376 sub git_shortlog {
9377 git_log_generic('shortlog', \&git_shortlog_body,
9378 $hash, $hash_parent);
9381 ## ......................................................................
9382 ## feeds (RSS, Atom; OPML)
9384 sub git_feed {
9385 my $format = shift || 'atom';
9386 my $have_blame = gitweb_check_feature('blame');
9388 # Atom: http://www.atomenabled.org/developers/syndication/
9389 # RSS: http://www.notestips.com/80256B3A007F2692/1/NAMO5P9UPQ
9390 if ($format ne 'rss' && $format ne 'atom') {
9391 die_error(400, "Unknown web feed format");
9394 # log/feed of current (HEAD) branch, log of given branch, history of file/directory
9395 my $head = $hash || 'HEAD';
9396 my @commitlist = parse_commits($head, 150, 0, $file_name);
9398 my %latest_commit;
9399 my %latest_date;
9400 my $content_type = "application/$format+xml";
9401 if (defined $cgi->http('HTTP_ACCEPT') &&
9402 $cgi->Accept('text/xml') > $cgi->Accept($content_type)) {
9403 # browser (feed reader) prefers text/xml
9404 $content_type = 'text/xml';
9406 if (defined($commitlist[0])) {
9407 %latest_commit = %{$commitlist[0]};
9408 my $latest_epoch = $latest_commit{'committer_epoch'};
9409 exit_if_unmodified_since($latest_epoch);
9410 %latest_date = parse_date($latest_epoch, $latest_commit{'committer_tz'});
9412 print $cgi->header(
9413 -type => $content_type,
9414 -charset => 'utf-8',
9415 %latest_date ? (-last_modified => $latest_date{'rfc2822'}) : (),
9416 -status => '200 OK');
9418 # Optimization: skip generating the body if client asks only
9419 # for Last-Modified date.
9420 return if ($cgi->request_method() eq 'HEAD');
9422 # header variables
9423 my $title = "$site_name - $project/$action";
9424 my $feed_type = 'log';
9425 if (defined $hash) {
9426 $title .= " - '$hash'";
9427 $feed_type = 'branch log';
9428 if (defined $file_name) {
9429 $title .= " :: $file_name";
9430 $feed_type = 'history';
9432 } elsif (defined $file_name) {
9433 $title .= " - $file_name";
9434 $feed_type = 'history';
9436 $title .= " $feed_type";
9437 $title = esc_html($title);
9438 my $descr = git_get_project_description($project);
9439 if (defined $descr) {
9440 $descr = esc_html($descr);
9441 } else {
9442 $descr = "$project " .
9443 ($format eq 'rss' ? 'RSS' : 'Atom') .
9444 " feed";
9446 my $owner = git_get_project_owner($project);
9447 $owner = esc_html($owner);
9449 #header
9450 my $alt_url;
9451 if (defined $file_name) {
9452 $alt_url = href(-full=>1, action=>"history", hash=>$hash, file_name=>$file_name);
9453 } elsif (defined $hash) {
9454 $alt_url = href(-full=>1, action=>"log", hash=>$hash);
9455 } else {
9456 $alt_url = href(-full=>1, action=>"summary");
9458 print qq!<?xml version="1.0" encoding="utf-8"?>\n!;
9459 if ($format eq 'rss') {
9460 print <<XML;
9461 <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
9462 <channel>
9464 print "<title>$title</title>\n" .
9465 "<link>$alt_url</link>\n" .
9466 "<description>$descr</description>\n" .
9467 "<language>en</language>\n" .
9468 # project owner is responsible for 'editorial' content
9469 "<managingEditor>$owner</managingEditor>\n";
9470 if (defined $logo || defined $favicon) {
9471 # prefer the logo to the favicon, since RSS
9472 # doesn't allow both
9473 my $img = esc_url($logo || $favicon);
9474 print "<image>\n" .
9475 "<url>$img</url>\n" .
9476 "<title>$title</title>\n" .
9477 "<link>$alt_url</link>\n" .
9478 "</image>\n";
9480 if (%latest_date) {
9481 print "<pubDate>$latest_date{'rfc2822'}</pubDate>\n";
9482 print "<lastBuildDate>$latest_date{'rfc2822'}</lastBuildDate>\n";
9484 print "<generator>gitweb v.$version/$git_version</generator>\n";
9485 } elsif ($format eq 'atom') {
9486 print <<XML;
9487 <feed xmlns="http://www.w3.org/2005/Atom">
9489 print "<title>$title</title>\n" .
9490 "<subtitle>$descr</subtitle>\n" .
9491 '<link rel="alternate" type="text/html" href="' .
9492 $alt_url . '" />' . "\n" .
9493 '<link rel="self" type="' . $content_type . '" href="' .
9494 $cgi->self_url() . '" />' . "\n" .
9495 "<id>" . href(-full=>1) . "</id>\n" .
9496 # use project owner for feed author
9497 '<author><name>'. email_obfuscate($owner) . '</name></author>\n';
9498 if (defined $favicon) {
9499 print "<icon>" . esc_url($favicon) . "</icon>\n";
9501 if (defined $logo) {
9502 # not twice as wide as tall: 72 x 27 pixels
9503 print "<logo>" . esc_url($logo) . "</logo>\n";
9505 if (! %latest_date) {
9506 # dummy date to keep the feed valid until commits trickle in:
9507 print "<updated>1970-01-01T00:00:00Z</updated>\n";
9508 } else {
9509 print "<updated>$latest_date{'iso-8601'}</updated>\n";
9511 print "<generator version='$version/$git_version'>gitweb</generator>\n";
9514 # contents
9515 for (my $i = 0; $i <= $#commitlist; $i++) {
9516 my %co = %{$commitlist[$i]};
9517 my $commit = $co{'id'};
9518 # we read 150, we always show 30 and the ones more recent than 48 hours
9519 if (($i >= 20) && ((time - $co{'author_epoch'}) > 48*60*60)) {
9520 last;
9522 my %cd = parse_date($co{'author_epoch'}, $co{'author_tz'});
9524 # get list of changed files
9525 defined(my $fd = git_cmd_pipe "diff-tree", '-r', @diff_opts,
9526 $co{'parent'} || "--root",
9527 $co{'id'}, "--", (defined $file_name ? $file_name : ()))
9528 or next;
9529 my @difftree = map { chomp; to_utf8($_) } <$fd>;
9530 close $fd
9531 or next;
9533 # print element (entry, item)
9534 my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
9535 if ($format eq 'rss') {
9536 print "<item>\n" .
9537 "<title>" . esc_html($co{'title'}) . "</title>\n" .
9538 "<author>" . esc_html($co{'author'}) . "</author>\n" .
9539 "<pubDate>$cd{'rfc2822'}</pubDate>\n" .
9540 "<guid isPermaLink=\"true\">$co_url</guid>\n" .
9541 "<link>$co_url</link>\n" .
9542 "<description>" . esc_html($co{'title'}) . "</description>\n" .
9543 "<content:encoded>" .
9544 "<![CDATA[\n";
9545 } elsif ($format eq 'atom') {
9546 print "<entry>\n" .
9547 "<title type=\"html\">" . esc_html($co{'title'}) . "</title>\n" .
9548 "<updated>$cd{'iso-8601'}</updated>\n" .
9549 "<author>\n" .
9550 " <name>" . esc_html($co{'author_name'}) . "</name>\n";
9551 if ($co{'author_email'}) {
9552 print " <email>" . esc_html($co{'author_email'}) . "</email>\n";
9554 print "</author>\n" .
9555 # use committer for contributor
9556 "<contributor>\n" .
9557 " <name>" . esc_html($co{'committer_name'}) . "</name>\n";
9558 if ($co{'committer_email'}) {
9559 print " <email>" . esc_html($co{'committer_email'}) . "</email>\n";
9561 print "</contributor>\n" .
9562 "<published>$cd{'iso-8601'}</published>\n" .
9563 "<link rel=\"alternate\" type=\"text/html\" href=\"$co_url\" />\n" .
9564 "<id>$co_url</id>\n" .
9565 "<content type=\"xhtml\" xml:base=\"" . esc_url($my_url) . "\">\n" .
9566 "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n";
9568 my $comment = $co{'comment'};
9569 print "<pre>\n";
9570 foreach my $line (@$comment) {
9571 $line = esc_html($line);
9572 print "$line\n";
9574 print "</pre><ul>\n";
9575 foreach my $difftree_line (@difftree) {
9576 my %difftree = parse_difftree_raw_line($difftree_line);
9577 next if !$difftree{'from_id'};
9579 my $file = $difftree{'file'} || $difftree{'to_file'};
9581 print "<li>" .
9582 "[" .
9583 $cgi->a({-href => href(-full=>1, action=>"blobdiff",
9584 hash=>$difftree{'to_id'}, hash_parent=>$difftree{'from_id'},
9585 hash_base=>$co{'id'}, hash_parent_base=>$co{'parent'},
9586 file_name=>$file, file_parent=>$difftree{'from_file'}),
9587 -title => "diff"}, 'D');
9588 if ($have_blame) {
9589 print $cgi->a({-href => href(-full=>1, action=>"blame",
9590 file_name=>$file, hash_base=>$commit),
9591 -class => "blamelink",
9592 -title => "blame"}, 'B');
9594 # if this is not a feed of a file history
9595 if (!defined $file_name || $file_name ne $file) {
9596 print $cgi->a({-href => href(-full=>1, action=>"history",
9597 file_name=>$file, hash=>$commit),
9598 -title => "history"}, 'H');
9600 $file = esc_path($file);
9601 print "] ".
9602 "$file</li>\n";
9604 if ($format eq 'rss') {
9605 print "</ul>]]>\n" .
9606 "</content:encoded>\n" .
9607 "</item>\n";
9608 } elsif ($format eq 'atom') {
9609 print "</ul>\n</div>\n" .
9610 "</content>\n" .
9611 "</entry>\n";
9615 # end of feed
9616 if ($format eq 'rss') {
9617 print "</channel>\n</rss>\n";
9618 } elsif ($format eq 'atom') {
9619 print "</feed>\n";
9623 sub git_rss {
9624 git_feed('rss');
9627 sub git_atom {
9628 git_feed('atom');
9631 sub git_opml {
9632 my @list = git_get_projects_list($project_filter, $strict_export);
9633 if (!@list) {
9634 die_error(404, "No projects found");
9637 print $cgi->header(
9638 -type => 'text/xml',
9639 -charset => 'utf-8',
9640 -content_disposition => 'inline; filename="opml.xml"');
9642 my $title = esc_html($site_name);
9643 my $filter = " within subdirectory ";
9644 if (defined $project_filter) {
9645 $filter .= esc_html($project_filter);
9646 } else {
9647 $filter = "";
9649 print <<XML;
9650 <?xml version="1.0" encoding="utf-8"?>
9651 <opml version="1.0">
9652 <head>
9653 <title>$title OPML Export$filter</title>
9654 </head>
9655 <body>
9656 <outline text="git RSS feeds">
9659 foreach my $pr (@list) {
9660 my %proj = %$pr;
9661 my $head = git_get_head_hash($proj{'path'});
9662 if (!defined $head) {
9663 next;
9665 $git_dir = "$projectroot/$proj{'path'}";
9666 my %co = parse_commit($head);
9667 if (!%co) {
9668 next;
9671 my $path = esc_html(chop_str($proj{'path'}, 25, 5));
9672 my $rss = href('project' => $proj{'path'}, 'action' => 'rss', -full => 1);
9673 my $html = href('project' => $proj{'path'}, 'action' => 'summary', -full => 1);
9674 print "<outline type=\"rss\" text=\"$path\" title=\"$path\" xmlUrl=\"$rss\" htmlUrl=\"$html\"/>\n";
9676 print <<XML;
9677 </outline>
9678 </body>
9679 </opml>