hgwebdir_mod.py
331 lines
| 12.7 KiB
| text/x-python
|
PythonLexer
|
r2391 | # hgweb/hgwebdir_mod.py - Web interface for a directory of repositories. | ||
|
r2356 | # | ||
# Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net> | ||||
|
r2859 | # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com> | ||
|
r2356 | # | ||
|
r8225 | # This software may be used and distributed according to the terms of the | ||
# GNU General Public License version 2, incorporated herein by reference. | ||||
|
r2356 | |||
|
r8371 | import os, time | ||
|
r7225 | from mercurial.i18n import _ | ||
|
r8360 | from mercurial import ui, hg, util, templater | ||
|
r8345 | from mercurial import error, encoding | ||
|
r7966 | from common import ErrorResponse, get_mtime, staticfile, paritygen,\ | ||
|
r5993 | get_contact, HTTP_OK, HTTP_NOT_FOUND, HTTP_SERVER_ERROR | ||
|
r3877 | from hgweb_mod import hgweb | ||
|
r5566 | from request import wsgirequest | ||
|
r8216 | import webutil | ||
|
r2356 | |||
|
r8215 | def cleannames(items): | ||
return [(util.pconvert(name).strip('/'), path) for name, path in items] | ||||
|
r2356 | |||
|
r8529 | def findrepos(paths): | ||
repos = {} | ||||
for prefix, root in cleannames(paths): | ||||
roothead, roottail = os.path.split(root) | ||||
# "foo = /bar/*" makes every subrepo of /bar/ to be | ||||
# mounted as foo/subrepo | ||||
# and "foo = /bar/**" also recurses into the subdirectories, | ||||
# remember to use it without working dir. | ||||
try: | ||||
recurse = {'*': False, '**': True}[roottail] | ||||
except KeyError: | ||||
repos[prefix] = root | ||||
continue | ||||
roothead = os.path.normpath(roothead) | ||||
for path in util.walkrepos(roothead, followsym=True, recurse=recurse): | ||||
path = os.path.normpath(path) | ||||
name = util.pconvert(path[len(roothead):]).strip('/') | ||||
if prefix: | ||||
name = prefix + '/' + name | ||||
repos[name] = path | ||||
return repos.items() | ||||
|
r2356 | class hgwebdir(object): | ||
|
r8371 | refreshinterval = 20 | ||
|
r8215 | |||
|
r8191 | def __init__(self, conf, baseui=None): | ||
|
r8371 | self.conf = conf | ||
self.baseui = baseui | ||||
self.lastrefresh = 0 | ||||
self.refresh() | ||||
|
r2356 | |||
|
r8371 | def refresh(self): | ||
if self.lastrefresh + self.refreshinterval > time.time(): | ||||
return | ||||
if self.baseui: | ||||
self.ui = self.baseui.copy() | ||||
|
r2356 | else: | ||
|
r8191 | self.ui = ui.ui() | ||
self.ui.setconfig('ui', 'report_untrusted', 'off') | ||||
self.ui.setconfig('ui', 'interactive', 'off') | ||||
|
r8136 | |||
|
r8529 | if not isinstance(self.conf, (dict, list, tuple)): | ||
map = {'paths': 'hgweb-paths'} | ||||
self.ui.readconfig(self.conf, remap=map, trust=True) | ||||
paths = self.ui.configitems('hgweb-paths') | ||||
elif isinstance(self.conf, (list, tuple)): | ||||
paths = self.conf | ||||
elif isinstance(self.conf, dict): | ||||
paths = self.conf.items() | ||||
|
r8345 | |||
|
r8859 | encoding.encoding = self.ui.config('web', 'encoding', | ||
encoding.encoding) | ||||
|
r8621 | self.motd = self.ui.config('web', 'motd') | ||
self.style = self.ui.config('web', 'style', 'paper') | ||||
self.stripecount = self.ui.config('web', 'stripes', 1) | ||||
if self.stripecount: | ||||
self.stripecount = int(self.stripecount) | ||||
self._baseurl = self.ui.config('web', 'baseurl') | ||||
|
r8529 | self.repos = findrepos(paths) | ||
|
r8345 | for prefix, root in self.ui.configitems('collections'): | ||
|
r8537 | prefix = util.pconvert(prefix) | ||
|
r8389 | for path in util.walkrepos(root, followsym=True): | ||
repo = os.path.normpath(path) | ||||
|
r8537 | name = util.pconvert(repo) | ||
|
r8389 | if name.startswith(prefix): | ||
name = name[len(prefix):] | ||||
|
r8537 | self.repos.append((name.lstrip('/'), repo)) | ||
|
r8345 | |||
self.repos.sort() | ||||
|
r8371 | self.lastrefresh = time.time() | ||
|
r2356 | |||
|
r2535 | def run(self): | ||
|
r2538 | if not os.environ.get('GATEWAY_INTERFACE', '').startswith("CGI/1."): | ||
|
r8663 | raise RuntimeError("This function is only intended to be " | ||
"called while running as a CGI script.") | ||||
|
r2535 | import mercurial.hgweb.wsgicgi as wsgicgi | ||
|
r5566 | wsgicgi.launch(self) | ||
def __call__(self, env, respond): | ||||
req = wsgirequest(env, respond) | ||||
|
r6797 | return self.run_wsgi(req) | ||
|
r2535 | |||
|
r7336 | def read_allowed(self, ui, req): | ||
"""Check allow_read and deny_read config options of a repo's ui object | ||||
to determine user permissions. By default, with neither option set (or | ||||
both empty), allow all users to read the repo. There are two ways a | ||||
user can be denied read access: (1) deny_read is not empty, and the | ||||
user is unauthenticated or deny_read contains user (or *), and (2) | ||||
allow_read is not empty and the user is not in allow_read. Return True | ||||
if user is allowed to read the repo, else return False.""" | ||||
user = req.env.get('REMOTE_USER') | ||||
|
r7575 | deny_read = ui.configlist('web', 'deny_read', untrusted=True) | ||
|
r7336 | if deny_read and (not user or deny_read == ['*'] or user in deny_read): | ||
return False | ||||
|
r7575 | allow_read = ui.configlist('web', 'allow_read', untrusted=True) | ||
|
r7336 | # by default, allow reading if no allow_read option has been set | ||
if (not allow_read) or (allow_read == ['*']) or (user in allow_read): | ||||
return True | ||||
return False | ||||
|
r2535 | def run_wsgi(self, req): | ||
|
r5601 | try: | ||
try: | ||||
|
r8371 | self.refresh() | ||
|
r5603 | |||
|
r5601 | virtual = req.env.get("PATH_INFO", "").strip('/') | ||
|
r5993 | tmpl = self.templater(req) | ||
|
r7948 | ctype = tmpl('mimetype', encoding=encoding.encoding) | ||
|
r6391 | ctype = templater.stringify(ctype) | ||
|
r5760 | |||
|
r5603 | # a static file | ||
if virtual.startswith('static/') or 'static' in req.form: | ||||
if virtual.startswith('static/'): | ||||
fname = virtual[7:] | ||||
else: | ||||
fname = req.form['static'][0] | ||||
|
r7107 | static = templater.templatepath('static') | ||
|
r7560 | return (staticfile(static, fname, req),) | ||
|
r5603 | |||
# top-level index | ||||
elif not virtual: | ||||
|
r5993 | req.respond(HTTP_OK, ctype) | ||
|
r7396 | return self.makeindex(req, tmpl) | ||
|
r5601 | |||
|
r5603 | # nested indexes and hgwebs | ||
|
r6210 | |||
|
r5603 | repos = dict(self.repos) | ||
while virtual: | ||||
real = repos.get(virtual) | ||||
if real: | ||||
req.env['REPO_NAME'] = virtual | ||||
try: | ||||
|
r8191 | repo = hg.repository(self.ui, real) | ||
|
r6797 | return hgweb(repo).run_wsgi(req) | ||
|
r5603 | except IOError, inst: | ||
|
r5993 | msg = inst.strerror | ||
raise ErrorResponse(HTTP_SERVER_ERROR, msg) | ||||
|
r7637 | except error.RepoError, inst: | ||
|
r5993 | raise ErrorResponse(HTTP_SERVER_ERROR, str(inst)) | ||
|
r5601 | |||
|
r5603 | # browse subdirectories | ||
subdir = virtual + '/' | ||||
if [r for r in repos if r.startswith(subdir)]: | ||||
|
r5993 | req.respond(HTTP_OK, ctype) | ||
|
r7396 | return self.makeindex(req, tmpl, subdir) | ||
|
r5603 | |||
up = virtual.rfind('/') | ||||
if up < 0: | ||||
break | ||||
virtual = virtual[:up] | ||||
# prefixes not found | ||||
|
r5993 | req.respond(HTTP_NOT_FOUND, ctype) | ||
|
r7396 | return tmpl("notfound", repo=virtual) | ||
|
r5760 | |||
|
r5601 | except ErrorResponse, err: | ||
|
r7740 | req.respond(err, ctype) | ||
|
r7396 | return tmpl('error', error=err.message or '') | ||
|
r5601 | finally: | ||
tmpl = None | ||||
def makeindex(self, req, tmpl, subdir=""): | ||||
|
r2356 | def archivelist(ui, nodeid, url): | ||
|
r3556 | allowed = ui.configlist("web", "allow_archive", untrusted=True) | ||
|
r3262 | for i in [('zip', '.zip'), ('gz', '.tar.gz'), ('bz2', '.tar.bz2')]: | ||
|
r3556 | if i[0] in allowed or ui.configbool("web", "allow" + i[0], | ||
untrusted=True): | ||||
|
r3262 | yield {"type" : i[0], "extension": i[1], | ||
"node": nodeid, "url": url} | ||||
|
r2356 | |||
|
r8346 | sortdefault = 'name', False | ||
|
r4841 | def entries(sortcolumn="", descending=False, subdir="", **map): | ||
|
r2356 | rows = [] | ||
|
r4462 | parity = paritygen(self.stripecount) | ||
|
r2356 | for name, path in self.repos: | ||
|
r4841 | if not name.startswith(subdir): | ||
continue | ||||
|
r4843 | name = name[len(subdir):] | ||
|
r4841 | |||
|
r8191 | u = self.ui.copy() | ||
|
r2356 | try: | ||
u.readconfig(os.path.join(path, '.hg', 'hgrc')) | ||||
|
r5332 | except Exception, e: | ||
|
r6913 | u.warn(_('error reading %s/.hg/hgrc: %s\n') % (path, e)) | ||
|
r5332 | continue | ||
|
r3556 | def get(section, name, default=None): | ||
return u.config(section, name, default, untrusted=True) | ||||
|
r2356 | |||
|
r4709 | if u.configbool("web", "hidden", untrusted=True): | ||
continue | ||||
|
r7336 | if not self.read_allowed(u, req): | ||
continue | ||||
|
r6459 | parts = [name] | ||
if 'PATH_INFO' in req.env: | ||||
parts.insert(0, req.env['PATH_INFO'].rstrip('/')) | ||||
|
r5579 | if req.env['SCRIPT_NAME']: | ||
|
r5760 | parts.insert(0, req.env['SCRIPT_NAME']) | ||
|
r5579 | url = ('/'.join(parts).replace("//", "/")) + '/' | ||
|
r2356 | |||
# update time with local timezone | ||||
try: | ||||
d = (get_mtime(path), util.makedate()[1]) | ||||
except OSError: | ||||
continue | ||||
|
r5779 | contact = get_contact(get) | ||
|
r2356 | description = get("web", "description", "") | ||
name = get("web", "name", name) | ||||
row = dict(contact=contact or "unknown", | ||||
contact_sort=contact.upper() or "unknown", | ||||
name=name, | ||||
name_sort=name, | ||||
url=url, | ||||
description=description or "unknown", | ||||
description_sort=description.upper() or "unknown", | ||||
lastchange=d, | ||||
lastchange_sort=d[1]-d[0], | ||||
archives=archivelist(u, "tip", url)) | ||||
|
r8346 | if (not sortcolumn or (sortcolumn, descending) == sortdefault): | ||
|
r2356 | # fast path for unsorted output | ||
|
r4462 | row['parity'] = parity.next() | ||
|
r2356 | yield row | ||
else: | ||||
rows.append((row["%s_sort" % sortcolumn], row)) | ||||
if rows: | ||||
rows.sort() | ||||
if descending: | ||||
rows.reverse() | ||||
for key, row in rows: | ||||
|
r4462 | row['parity'] = parity.next() | ||
|
r2356 | yield row | ||
|
r8371 | self.refresh() | ||
|
r5601 | sortable = ["name", "description", "contact", "lastchange"] | ||
|
r8346 | sortcolumn, descending = sortdefault | ||
|
r5915 | if 'sort' in req.form: | ||
|
r5601 | sortcolumn = req.form['sort'][0] | ||
descending = sortcolumn.startswith('-') | ||||
if descending: | ||||
sortcolumn = sortcolumn[1:] | ||||
if sortcolumn not in sortable: | ||||
sortcolumn = "" | ||||
|
r4841 | |||
|
r5601 | sort = [("sort_%s" % column, | ||
"%s%s" % ((not descending and column == sortcolumn) | ||||
and "-" or "", column)) | ||||
for column in sortable] | ||||
|
r5928 | |||
|
r8371 | self.refresh() | ||
|
r6221 | if self._baseurl is not None: | ||
req.env['SCRIPT_NAME'] = self._baseurl | ||||
|
r5965 | return tmpl("index", entries=entries, subdir=subdir, | ||
sortcolumn=sortcolumn, descending=descending, | ||||
**dict(sort)) | ||||
|
r5602 | |||
def templater(self, req): | ||||
def header(**map): | ||||
|
r7948 | yield tmpl('header', encoding=encoding.encoding, **map) | ||
|
r5602 | |||
def footer(**map): | ||||
yield tmpl("footer", **map) | ||||
def motd(**map): | ||||
if self.motd is not None: | ||||
yield self.motd | ||||
else: | ||||
yield config('web', 'motd', '') | ||||
def config(section, name, default=None, untrusted=True): | ||||
|
r8191 | return self.ui.config(section, name, default, untrusted) | ||
|
r5602 | |||
|
r6221 | if self._baseurl is not None: | ||
req.env['SCRIPT_NAME'] = self._baseurl | ||||
|
r5602 | url = req.env.get('SCRIPT_NAME', '') | ||
if not url.endswith('/'): | ||||
url += '/' | ||||
|
r8216 | vars = {} | ||
style = self.style | ||||
if 'style' in req.form: | ||||
vars['style'] = style = req.form['style'][0] | ||||
start = url[-1] == '?' and '&' or '?' | ||||
sessionvars = webutil.sessionvars(vars, start) | ||||
|
r5602 | staticurl = config('web', 'staticurl') or url + 'static/' | ||
if not staticurl.endswith('/'): | ||||
staticurl += '/' | ||||
|
r8215 | style = 'style' in req.form and req.form['style'][0] or self.style | ||
|
r7966 | mapfile = templater.stylemap(style) | ||
|
r8360 | tmpl = templater.templater(mapfile, | ||
|
r5602 | defaults={"header": header, | ||
"footer": footer, | ||||
"motd": motd, | ||||
"url": url, | ||||
|
r8216 | "staticurl": staticurl, | ||
"sessionvars": sessionvars}) | ||||
|
r5602 | return tmpl | ||