hgwebdir_mod.py
331 lines
| 12.7 KiB
| text/x-python
|
PythonLexer
Eric Hopper
|
r2391 | # hgweb/hgwebdir_mod.py - Web interface for a directory of repositories. | ||
Eric Hopper
|
r2356 | # | ||
# Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net> | ||||
Vadim Gelfer
|
r2859 | # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com> | ||
Eric Hopper
|
r2356 | # | ||
Martin Geisler
|
r8225 | # This software may be used and distributed according to the terms of the | ||
# GNU General Public License version 2, incorporated herein by reference. | ||||
Eric Hopper
|
r2356 | |||
Bryan O'Sullivan
|
r8371 | import os, time | ||
Martin Geisler
|
r7225 | from mercurial.i18n import _ | ||
Dirkjan Ochtman
|
r8360 | from mercurial import ui, hg, util, templater | ||
Alexander Solovyov
|
r8345 | from mercurial import error, encoding | ||
Dirkjan Ochtman
|
r7966 | from common import ErrorResponse, get_mtime, staticfile, paritygen,\ | ||
Dirkjan Ochtman
|
r5993 | get_contact, HTTP_OK, HTTP_NOT_FOUND, HTTP_SERVER_ERROR | ||
Matt Mackall
|
r3877 | from hgweb_mod import hgweb | ||
Dirkjan Ochtman
|
r5566 | from request import wsgirequest | ||
Dirkjan Ochtman
|
r8216 | import webutil | ||
Eric Hopper
|
r2356 | |||
Dirkjan Ochtman
|
r8215 | def cleannames(items): | ||
return [(util.pconvert(name).strip('/'), path) for name, path in items] | ||||
Eric Hopper
|
r2356 | |||
Jeremy Whitlock
|
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() | ||||
Eric Hopper
|
r2356 | class hgwebdir(object): | ||
Bryan O'Sullivan
|
r8371 | refreshinterval = 20 | ||
Dirkjan Ochtman
|
r8215 | |||
Matt Mackall
|
r8191 | def __init__(self, conf, baseui=None): | ||
Bryan O'Sullivan
|
r8371 | self.conf = conf | ||
self.baseui = baseui | ||||
self.lastrefresh = 0 | ||||
self.refresh() | ||||
Eric Hopper
|
r2356 | |||
Bryan O'Sullivan
|
r8371 | def refresh(self): | ||
if self.lastrefresh + self.refreshinterval > time.time(): | ||||
return | ||||
if self.baseui: | ||||
self.ui = self.baseui.copy() | ||||
Eric Hopper
|
r2356 | else: | ||
Matt Mackall
|
r8191 | self.ui = ui.ui() | ||
self.ui.setconfig('ui', 'report_untrusted', 'off') | ||||
self.ui.setconfig('ui', 'interactive', 'off') | ||||
Matt Mackall
|
r8136 | |||
Jeremy Whitlock
|
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() | ||||
Alexander Solovyov
|
r8345 | |||
Matt Mackall
|
r8859 | encoding.encoding = self.ui.config('web', 'encoding', | ||
encoding.encoding) | ||||
Dirkjan Ochtman
|
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') | ||||
Jeremy Whitlock
|
r8529 | self.repos = findrepos(paths) | ||
Alexander Solovyov
|
r8345 | for prefix, root in self.ui.configitems('collections'): | ||
Patrick Mezard
|
r8537 | prefix = util.pconvert(prefix) | ||
Peter Arrenbrecht
|
r8389 | for path in util.walkrepos(root, followsym=True): | ||
repo = os.path.normpath(path) | ||||
Patrick Mezard
|
r8537 | name = util.pconvert(repo) | ||
Peter Arrenbrecht
|
r8389 | if name.startswith(prefix): | ||
name = name[len(prefix):] | ||||
Patrick Mezard
|
r8537 | self.repos.append((name.lstrip('/'), repo)) | ||
Alexander Solovyov
|
r8345 | |||
self.repos.sort() | ||||
Bryan O'Sullivan
|
r8371 | self.lastrefresh = time.time() | ||
Eric Hopper
|
r2356 | |||
Eric Hopper
|
r2535 | def run(self): | ||
Eric Hopper
|
r2538 | if not os.environ.get('GATEWAY_INTERFACE', '').startswith("CGI/1."): | ||
Martin Geisler
|
r8663 | raise RuntimeError("This function is only intended to be " | ||
"called while running as a CGI script.") | ||||
Eric Hopper
|
r2535 | import mercurial.hgweb.wsgicgi as wsgicgi | ||
Dirkjan Ochtman
|
r5566 | wsgicgi.launch(self) | ||
def __call__(self, env, respond): | ||||
req = wsgirequest(env, respond) | ||||
Dirkjan Ochtman
|
r6797 | return self.run_wsgi(req) | ||
Eric Hopper
|
r2535 | |||
Mark Edgington
|
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') | ||||
Dirkjan Ochtman
|
r7575 | deny_read = ui.configlist('web', 'deny_read', untrusted=True) | ||
Mark Edgington
|
r7336 | if deny_read and (not user or deny_read == ['*'] or user in deny_read): | ||
return False | ||||
Dirkjan Ochtman
|
r7575 | allow_read = ui.configlist('web', 'allow_read', untrusted=True) | ||
Mark Edgington
|
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 | ||||
Eric Hopper
|
r2535 | def run_wsgi(self, req): | ||
Dirkjan Ochtman
|
r5601 | try: | ||
try: | ||||
Bryan O'Sullivan
|
r8371 | self.refresh() | ||
Dirkjan Ochtman
|
r5603 | |||
Dirkjan Ochtman
|
r5601 | virtual = req.env.get("PATH_INFO", "").strip('/') | ||
Dirkjan Ochtman
|
r5993 | tmpl = self.templater(req) | ||
Matt Mackall
|
r7948 | ctype = tmpl('mimetype', encoding=encoding.encoding) | ||
Dirkjan Ochtman
|
r6391 | ctype = templater.stringify(ctype) | ||
Thomas Arendsen Hein
|
r5760 | |||
Dirkjan Ochtman
|
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] | ||||
Brendan Cully
|
r7107 | static = templater.templatepath('static') | ||
Patrick Mezard
|
r7560 | return (staticfile(static, fname, req),) | ||
Dirkjan Ochtman
|
r5603 | |||
# top-level index | ||||
elif not virtual: | ||||
Dirkjan Ochtman
|
r5993 | req.respond(HTTP_OK, ctype) | ||
Brendan Cully
|
r7396 | return self.makeindex(req, tmpl) | ||
Dirkjan Ochtman
|
r5601 | |||
Dirkjan Ochtman
|
r5603 | # nested indexes and hgwebs | ||
Thomas Arendsen Hein
|
r6210 | |||
Dirkjan Ochtman
|
r5603 | repos = dict(self.repos) | ||
while virtual: | ||||
real = repos.get(virtual) | ||||
if real: | ||||
req.env['REPO_NAME'] = virtual | ||||
try: | ||||
Matt Mackall
|
r8191 | repo = hg.repository(self.ui, real) | ||
Dirkjan Ochtman
|
r6797 | return hgweb(repo).run_wsgi(req) | ||
Dirkjan Ochtman
|
r5603 | except IOError, inst: | ||
Dirkjan Ochtman
|
r5993 | msg = inst.strerror | ||
raise ErrorResponse(HTTP_SERVER_ERROR, msg) | ||||
Matt Mackall
|
r7637 | except error.RepoError, inst: | ||
Dirkjan Ochtman
|
r5993 | raise ErrorResponse(HTTP_SERVER_ERROR, str(inst)) | ||
Dirkjan Ochtman
|
r5601 | |||
Dirkjan Ochtman
|
r5603 | # browse subdirectories | ||
subdir = virtual + '/' | ||||
if [r for r in repos if r.startswith(subdir)]: | ||||
Dirkjan Ochtman
|
r5993 | req.respond(HTTP_OK, ctype) | ||
Brendan Cully
|
r7396 | return self.makeindex(req, tmpl, subdir) | ||
Dirkjan Ochtman
|
r5603 | |||
up = virtual.rfind('/') | ||||
if up < 0: | ||||
break | ||||
virtual = virtual[:up] | ||||
# prefixes not found | ||||
Dirkjan Ochtman
|
r5993 | req.respond(HTTP_NOT_FOUND, ctype) | ||
Brendan Cully
|
r7396 | return tmpl("notfound", repo=virtual) | ||
Thomas Arendsen Hein
|
r5760 | |||
Dirkjan Ochtman
|
r5601 | except ErrorResponse, err: | ||
Dirkjan Ochtman
|
r7740 | req.respond(err, ctype) | ||
Brendan Cully
|
r7396 | return tmpl('error', error=err.message or '') | ||
Dirkjan Ochtman
|
r5601 | finally: | ||
tmpl = None | ||||
def makeindex(self, req, tmpl, subdir=""): | ||||
Eric Hopper
|
r2356 | def archivelist(ui, nodeid, url): | ||
Alexis S. L. Carvalho
|
r3556 | allowed = ui.configlist("web", "allow_archive", untrusted=True) | ||
Brendan Cully
|
r3262 | for i in [('zip', '.zip'), ('gz', '.tar.gz'), ('bz2', '.tar.bz2')]: | ||
Alexis S. L. Carvalho
|
r3556 | if i[0] in allowed or ui.configbool("web", "allow" + i[0], | ||
untrusted=True): | ||||
Brendan Cully
|
r3262 | yield {"type" : i[0], "extension": i[1], | ||
"node": nodeid, "url": url} | ||||
Eric Hopper
|
r2356 | |||
Dirkjan Ochtman
|
r8346 | sortdefault = 'name', False | ||
Brendan Cully
|
r4841 | def entries(sortcolumn="", descending=False, subdir="", **map): | ||
Eric Hopper
|
r2356 | rows = [] | ||
Thomas Arendsen Hein
|
r4462 | parity = paritygen(self.stripecount) | ||
Eric Hopper
|
r2356 | for name, path in self.repos: | ||
Brendan Cully
|
r4841 | if not name.startswith(subdir): | ||
continue | ||||
Brendan Cully
|
r4843 | name = name[len(subdir):] | ||
Brendan Cully
|
r4841 | |||
Matt Mackall
|
r8191 | u = self.ui.copy() | ||
Eric Hopper
|
r2356 | try: | ||
u.readconfig(os.path.join(path, '.hg', 'hgrc')) | ||||
Alexis S. L. Carvalho
|
r5332 | except Exception, e: | ||
Martin Geisler
|
r6913 | u.warn(_('error reading %s/.hg/hgrc: %s\n') % (path, e)) | ||
Alexis S. L. Carvalho
|
r5332 | continue | ||
Alexis S. L. Carvalho
|
r3556 | def get(section, name, default=None): | ||
return u.config(section, name, default, untrusted=True) | ||||
Eric Hopper
|
r2356 | |||
Markus F.X.J. Oberhumer
|
r4709 | if u.configbool("web", "hidden", untrusted=True): | ||
continue | ||||
Mark Edgington
|
r7336 | if not self.read_allowed(u, req): | ||
continue | ||||
Dirkjan Ochtman
|
r6459 | parts = [name] | ||
if 'PATH_INFO' in req.env: | ||||
parts.insert(0, req.env['PATH_INFO'].rstrip('/')) | ||||
Dirkjan Ochtman
|
r5579 | if req.env['SCRIPT_NAME']: | ||
Thomas Arendsen Hein
|
r5760 | parts.insert(0, req.env['SCRIPT_NAME']) | ||
Dirkjan Ochtman
|
r5579 | url = ('/'.join(parts).replace("//", "/")) + '/' | ||
Eric Hopper
|
r2356 | |||
# update time with local timezone | ||||
try: | ||||
d = (get_mtime(path), util.makedate()[1]) | ||||
except OSError: | ||||
continue | ||||
Thomas Arendsen Hein
|
r5779 | contact = get_contact(get) | ||
Eric Hopper
|
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)) | ||||
Dirkjan Ochtman
|
r8346 | if (not sortcolumn or (sortcolumn, descending) == sortdefault): | ||
Eric Hopper
|
r2356 | # fast path for unsorted output | ||
Thomas Arendsen Hein
|
r4462 | row['parity'] = parity.next() | ||
Eric Hopper
|
r2356 | yield row | ||
else: | ||||
rows.append((row["%s_sort" % sortcolumn], row)) | ||||
if rows: | ||||
rows.sort() | ||||
if descending: | ||||
rows.reverse() | ||||
for key, row in rows: | ||||
Thomas Arendsen Hein
|
r4462 | row['parity'] = parity.next() | ||
Eric Hopper
|
r2356 | yield row | ||
Bryan O'Sullivan
|
r8371 | self.refresh() | ||
Dirkjan Ochtman
|
r5601 | sortable = ["name", "description", "contact", "lastchange"] | ||
Dirkjan Ochtman
|
r8346 | sortcolumn, descending = sortdefault | ||
Christian Ebert
|
r5915 | if 'sort' in req.form: | ||
Dirkjan Ochtman
|
r5601 | sortcolumn = req.form['sort'][0] | ||
descending = sortcolumn.startswith('-') | ||||
if descending: | ||||
sortcolumn = sortcolumn[1:] | ||||
if sortcolumn not in sortable: | ||||
sortcolumn = "" | ||||
Brendan Cully
|
r4841 | |||
Dirkjan Ochtman
|
r5601 | sort = [("sort_%s" % column, | ||
"%s%s" % ((not descending and column == sortcolumn) | ||||
and "-" or "", column)) | ||||
for column in sortable] | ||||
Dirkjan Ochtman
|
r5928 | |||
Bryan O'Sullivan
|
r8371 | self.refresh() | ||
Brendan Cully
|
r6221 | if self._baseurl is not None: | ||
req.env['SCRIPT_NAME'] = self._baseurl | ||||
Dirkjan Ochtman
|
r5965 | return tmpl("index", entries=entries, subdir=subdir, | ||
sortcolumn=sortcolumn, descending=descending, | ||||
**dict(sort)) | ||||
Dirkjan Ochtman
|
r5602 | |||
def templater(self, req): | ||||
def header(**map): | ||||
Matt Mackall
|
r7948 | yield tmpl('header', encoding=encoding.encoding, **map) | ||
Dirkjan Ochtman
|
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): | ||||
Matt Mackall
|
r8191 | return self.ui.config(section, name, default, untrusted) | ||
Dirkjan Ochtman
|
r5602 | |||
Brendan Cully
|
r6221 | if self._baseurl is not None: | ||
req.env['SCRIPT_NAME'] = self._baseurl | ||||
Dirkjan Ochtman
|
r5602 | url = req.env.get('SCRIPT_NAME', '') | ||
if not url.endswith('/'): | ||||
url += '/' | ||||
Dirkjan Ochtman
|
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) | ||||
Dirkjan Ochtman
|
r5602 | staticurl = config('web', 'staticurl') or url + 'static/' | ||
if not staticurl.endswith('/'): | ||||
staticurl += '/' | ||||
Dirkjan Ochtman
|
r8215 | style = 'style' in req.form and req.form['style'][0] or self.style | ||
Dirkjan Ochtman
|
r7966 | mapfile = templater.stylemap(style) | ||
Dirkjan Ochtman
|
r8360 | tmpl = templater.templater(mapfile, | ||
Dirkjan Ochtman
|
r5602 | defaults={"header": header, | ||
"footer": footer, | ||||
"motd": motd, | ||||
"url": url, | ||||
Dirkjan Ochtman
|
r8216 | "staticurl": staticurl, | ||
"sessionvars": sessionvars}) | ||||
Dirkjan Ochtman
|
r5602 | return tmpl | ||