hgweb: rename req to wsgireq
authorGregory Szorc <gregory.szorc@gmail.com>
Thu, 08 Mar 2018 15:15:59 -0800
changeset 36804 b9b968e21f78
parent 36803 8e1556ac01bb
child 36805 ec46415ed826
hgweb: rename req to wsgireq We will soon introduce a parsed WSGI request object so we don't have to concern ourselves with low-level WSGI matters. Prepare for multiple request objects by renaming the existing one so it is clear it deals with WSGI. We also remove a symbol import to avoid even more naming confusion. # no-check-commit because of some new foo_bar naming that's required Differential Revision: https://phab.mercurial-scm.org/D2732
mercurial/hgweb/hgweb_mod.py
mercurial/hgweb/hgwebdir_mod.py
mercurial/wireprotoserver.py
--- a/mercurial/hgweb/hgweb_mod.py	Thu Mar 08 09:44:27 2018 -0800
+++ b/mercurial/hgweb/hgweb_mod.py	Thu Mar 08 15:15:59 2018 -0800
@@ -22,7 +22,6 @@
     cspvalues,
     permhooks,
 )
-from .request import wsgirequest
 
 from .. import (
     encoding,
@@ -41,6 +40,7 @@
 )
 
 from . import (
+    request as requestmod,
     webcommands,
     webutil,
     wsgicgi,
@@ -142,11 +142,11 @@
             if typ in allowed or self.configbool('web', 'allow%s' % typ):
                 yield {'type': typ, 'extension': spec[2], 'node': nodeid}
 
-    def templater(self, req):
+    def templater(self, wsgireq):
         # determine scheme, port and server name
         # this is needed to create absolute urls
 
-        proto = req.env.get('wsgi.url_scheme')
+        proto = wsgireq.env.get('wsgi.url_scheme')
         if proto == 'https':
             proto = 'https'
             default_port = '443'
@@ -154,13 +154,13 @@
             proto = 'http'
             default_port = '80'
 
-        port = req.env[r'SERVER_PORT']
+        port = wsgireq.env[r'SERVER_PORT']
         port = port != default_port and (r':' + port) or r''
-        urlbase = r'%s://%s%s' % (proto, req.env[r'SERVER_NAME'], port)
+        urlbase = r'%s://%s%s' % (proto, wsgireq.env[r'SERVER_NAME'], port)
         logourl = self.config('web', 'logourl')
         logoimg = self.config('web', 'logoimg')
         staticurl = (self.config('web', 'staticurl')
-                     or pycompat.sysbytes(req.url) + 'static/')
+                     or pycompat.sysbytes(wsgireq.url) + 'static/')
         if not staticurl.endswith('/'):
             staticurl += '/'
 
@@ -172,18 +172,18 @@
         # figure out which style to use
 
         vars = {}
-        styles, (style, mapfile) = getstyle(req, self.config,
+        styles, (style, mapfile) = getstyle(wsgireq, self.config,
                                             self.templatepath)
         if style == styles[0]:
             vars['style'] = style
 
-        start = '&' if req.url[-1] == r'?' else '?'
+        start = '&' if wsgireq.url[-1] == r'?' else '?'
         sessionvars = webutil.sessionvars(vars, start)
 
         if not self.reponame:
             self.reponame = (self.config('web', 'name', '')
-                             or req.env.get('REPO_NAME')
-                             or req.url.strip(r'/') or self.repo.root)
+                             or wsgireq.env.get('REPO_NAME')
+                             or wsgireq.url.strip(r'/') or self.repo.root)
 
         def websubfilter(text):
             return templatefilters.websub(text, self.websubtable)
@@ -191,7 +191,7 @@
         # create the templater
         # TODO: export all keywords: defaults = templatekw.keywords.copy()
         defaults = {
-            'url': pycompat.sysbytes(req.url),
+            'url': pycompat.sysbytes(wsgireq.url),
             'logourl': logourl,
             'logoimg': logoimg,
             'staticurl': staticurl,
@@ -200,7 +200,7 @@
             'encoding': encoding.encoding,
             'motd': motd,
             'sessionvars': sessionvars,
-            'pathdef': makebreadcrumb(pycompat.sysbytes(req.url)),
+            'pathdef': makebreadcrumb(pycompat.sysbytes(wsgireq.url)),
             'style': style,
             'nonce': self.nonce,
         }
@@ -301,10 +301,10 @@
 
         This may be called by multiple threads.
         """
-        req = wsgirequest(env, respond)
+        req = requestmod.wsgirequest(env, respond)
         return self.run_wsgi(req)
 
-    def run_wsgi(self, req):
+    def run_wsgi(self, wsgireq):
         """Internal method to run the WSGI application.
 
         This is typically only called by Mercurial. External consumers
@@ -313,45 +313,45 @@
         with self._obtainrepo() as repo:
             profile = repo.ui.configbool('profiling', 'enabled')
             with profiling.profile(repo.ui, enabled=profile):
-                for r in self._runwsgi(req, repo):
+                for r in self._runwsgi(wsgireq, repo):
                     yield r
 
-    def _runwsgi(self, req, repo):
+    def _runwsgi(self, wsgireq, repo):
         rctx = requestcontext(self, repo)
 
         # This state is global across all threads.
         encoding.encoding = rctx.config('web', 'encoding')
-        rctx.repo.ui.environ = req.env
+        rctx.repo.ui.environ = wsgireq.env
 
         if rctx.csp:
             # hgwebdir may have added CSP header. Since we generate our own,
             # replace it.
-            req.headers = [h for h in req.headers
-                           if h[0] != 'Content-Security-Policy']
-            req.headers.append(('Content-Security-Policy', rctx.csp))
+            wsgireq.headers = [h for h in wsgireq.headers
+                               if h[0] != 'Content-Security-Policy']
+            wsgireq.headers.append(('Content-Security-Policy', rctx.csp))
 
         # work with CGI variables to create coherent structure
         # use SCRIPT_NAME, PATH_INFO and QUERY_STRING as well as our REPO_NAME
 
-        req.url = req.env[r'SCRIPT_NAME']
-        if not req.url.endswith(r'/'):
-            req.url += r'/'
-        if req.env.get('REPO_NAME'):
-            req.url += req.env[r'REPO_NAME'] + r'/'
+        wsgireq.url = wsgireq.env[r'SCRIPT_NAME']
+        if not wsgireq.url.endswith(r'/'):
+            wsgireq.url += r'/'
+        if wsgireq.env.get('REPO_NAME'):
+            wsgireq.url += wsgireq.env[r'REPO_NAME'] + r'/'
 
-        if r'PATH_INFO' in req.env:
-            parts = req.env[r'PATH_INFO'].strip(r'/').split(r'/')
-            repo_parts = req.env.get(r'REPO_NAME', r'').split(r'/')
+        if r'PATH_INFO' in wsgireq.env:
+            parts = wsgireq.env[r'PATH_INFO'].strip(r'/').split(r'/')
+            repo_parts = wsgireq.env.get(r'REPO_NAME', r'').split(r'/')
             if parts[:len(repo_parts)] == repo_parts:
                 parts = parts[len(repo_parts):]
             query = r'/'.join(parts)
         else:
-            query = req.env[r'QUERY_STRING'].partition(r'&')[0]
+            query = wsgireq.env[r'QUERY_STRING'].partition(r'&')[0]
             query = query.partition(r';')[0]
 
         # Route it to a wire protocol handler if it looks like a wire protocol
         # request.
-        protohandler = wireprotoserver.parsehttprequest(rctx, req, query,
+        protohandler = wireprotoserver.parsehttprequest(rctx, wsgireq, query,
                                                         self.check_perm)
 
         if protohandler:
@@ -366,83 +366,83 @@
         # translate user-visible url structure to internal structure
 
         args = query.split(r'/', 2)
-        if 'cmd' not in req.form and args and args[0]:
+        if 'cmd' not in wsgireq.form and args and args[0]:
             cmd = args.pop(0)
             style = cmd.rfind('-')
             if style != -1:
-                req.form['style'] = [cmd[:style]]
+                wsgireq.form['style'] = [cmd[:style]]
                 cmd = cmd[style + 1:]
 
             # avoid accepting e.g. style parameter as command
             if util.safehasattr(webcommands, cmd):
-                req.form['cmd'] = [cmd]
+                wsgireq.form['cmd'] = [cmd]
 
             if cmd == 'static':
-                req.form['file'] = ['/'.join(args)]
+                wsgireq.form['file'] = ['/'.join(args)]
             else:
                 if args and args[0]:
                     node = args.pop(0).replace('%2F', '/')
-                    req.form['node'] = [node]
+                    wsgireq.form['node'] = [node]
                 if args:
-                    req.form['file'] = args
+                    wsgireq.form['file'] = args
 
-            ua = req.env.get('HTTP_USER_AGENT', '')
+            ua = wsgireq.env.get('HTTP_USER_AGENT', '')
             if cmd == 'rev' and 'mercurial' in ua:
-                req.form['style'] = ['raw']
+                wsgireq.form['style'] = ['raw']
 
             if cmd == 'archive':
-                fn = req.form['node'][0]
+                fn = wsgireq.form['node'][0]
                 for type_, spec in rctx.archivespecs.iteritems():
                     ext = spec[2]
                     if fn.endswith(ext):
-                        req.form['node'] = [fn[:-len(ext)]]
-                        req.form['type'] = [type_]
+                        wsgireq.form['node'] = [fn[:-len(ext)]]
+                        wsgireq.form['type'] = [type_]
         else:
-            cmd = req.form.get('cmd', [''])[0]
+            cmd = wsgireq.form.get('cmd', [''])[0]
 
         # process the web interface request
 
         try:
-            tmpl = rctx.templater(req)
+            tmpl = rctx.templater(wsgireq)
             ctype = tmpl('mimetype', encoding=encoding.encoding)
             ctype = templater.stringify(ctype)
 
             # check read permissions non-static content
             if cmd != 'static':
-                self.check_perm(rctx, req, None)
+                self.check_perm(rctx, wsgireq, None)
 
             if cmd == '':
-                req.form['cmd'] = [tmpl.cache['default']]
-                cmd = req.form['cmd'][0]
+                wsgireq.form['cmd'] = [tmpl.cache['default']]
+                cmd = wsgireq.form['cmd'][0]
 
             # Don't enable caching if using a CSP nonce because then it wouldn't
             # be a nonce.
             if rctx.configbool('web', 'cache') and not rctx.nonce:
-                caching(self, req) # sets ETag header or raises NOT_MODIFIED
+                caching(self, wsgireq) # sets ETag header or raises NOT_MODIFIED
             if cmd not in webcommands.__all__:
                 msg = 'no such method: %s' % cmd
                 raise ErrorResponse(HTTP_BAD_REQUEST, msg)
-            elif cmd == 'file' and 'raw' in req.form.get('style', []):
+            elif cmd == 'file' and 'raw' in wsgireq.form.get('style', []):
                 rctx.ctype = ctype
-                content = webcommands.rawfile(rctx, req, tmpl)
+                content = webcommands.rawfile(rctx, wsgireq, tmpl)
             else:
-                content = getattr(webcommands, cmd)(rctx, req, tmpl)
-                req.respond(HTTP_OK, ctype)
+                content = getattr(webcommands, cmd)(rctx, wsgireq, tmpl)
+                wsgireq.respond(HTTP_OK, ctype)
 
             return content
 
         except (error.LookupError, error.RepoLookupError) as err:
-            req.respond(HTTP_NOT_FOUND, ctype)
+            wsgireq.respond(HTTP_NOT_FOUND, ctype)
             msg = pycompat.bytestr(err)
             if (util.safehasattr(err, 'name') and
                 not isinstance(err,  error.ManifestLookupError)):
                 msg = 'revision not found: %s' % err.name
             return tmpl('error', error=msg)
         except (error.RepoError, error.RevlogError) as inst:
-            req.respond(HTTP_SERVER_ERROR, ctype)
+            wsgireq.respond(HTTP_SERVER_ERROR, ctype)
             return tmpl('error', error=pycompat.bytestr(inst))
         except ErrorResponse as inst:
-            req.respond(inst, ctype)
+            wsgireq.respond(inst, ctype)
             if inst.code == HTTP_NOT_MODIFIED:
                 # Not allowed to return a body on a 304
                 return ['']
--- a/mercurial/hgweb/hgwebdir_mod.py	Thu Mar 08 09:44:27 2018 -0800
+++ b/mercurial/hgweb/hgwebdir_mod.py	Thu Mar 08 15:15:59 2018 -0800
@@ -26,7 +26,6 @@
     paritygen,
     staticfile,
 )
-from .request import wsgirequest
 
 from .. import (
     configitems,
@@ -43,6 +42,7 @@
 
 from . import (
     hgweb_mod,
+    request as requestmod,
     webutil,
     wsgicgi,
 )
@@ -197,10 +197,10 @@
         wsgicgi.launch(self)
 
     def __call__(self, env, respond):
-        req = wsgirequest(env, respond)
-        return self.run_wsgi(req)
+        wsgireq = requestmod.wsgirequest(env, respond)
+        return self.run_wsgi(wsgireq)
 
-    def read_allowed(self, ui, req):
+    def read_allowed(self, ui, wsgireq):
         """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
@@ -209,7 +209,7 @@
         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')
+        user = wsgireq.env.get('REMOTE_USER')
 
         deny_read = ui.configlist('web', 'deny_read', untrusted=True)
         if deny_read and (not user or ismember(ui, user, deny_read)):
@@ -222,31 +222,31 @@
 
         return False
 
-    def run_wsgi(self, req):
+    def run_wsgi(self, wsgireq):
         profile = self.ui.configbool('profiling', 'enabled')
         with profiling.profile(self.ui, enabled=profile):
-            for r in self._runwsgi(req):
+            for r in self._runwsgi(wsgireq):
                 yield r
 
-    def _runwsgi(self, req):
+    def _runwsgi(self, wsgireq):
         try:
             self.refresh()
 
             csp, nonce = cspvalues(self.ui)
             if csp:
-                req.headers.append(('Content-Security-Policy', csp))
+                wsgireq.headers.append(('Content-Security-Policy', csp))
 
-            virtual = req.env.get("PATH_INFO", "").strip('/')
-            tmpl = self.templater(req, nonce)
+            virtual = wsgireq.env.get("PATH_INFO", "").strip('/')
+            tmpl = self.templater(wsgireq, nonce)
             ctype = tmpl('mimetype', encoding=encoding.encoding)
             ctype = templater.stringify(ctype)
 
             # a static file
-            if virtual.startswith('static/') or 'static' in req.form:
+            if virtual.startswith('static/') or 'static' in wsgireq.form:
                 if virtual.startswith('static/'):
                     fname = virtual[7:]
                 else:
-                    fname = req.form['static'][0]
+                    fname = wsgireq.form['static'][0]
                 static = self.ui.config("web", "static", None,
                                         untrusted=False)
                 if not static:
@@ -254,7 +254,7 @@
                     if isinstance(tp, str):
                         tp = [tp]
                     static = [os.path.join(p, 'static') for p in tp]
-                staticfile(static, fname, req)
+                staticfile(static, fname, wsgireq)
                 return []
 
             # top-level index
@@ -262,16 +262,16 @@
             repos = dict(self.repos)
 
             if (not virtual or virtual == 'index') and virtual not in repos:
-                req.respond(HTTP_OK, ctype)
-                return self.makeindex(req, tmpl)
+                wsgireq.respond(HTTP_OK, ctype)
+                return self.makeindex(wsgireq, tmpl)
 
             # nested indexes and hgwebs
 
             if virtual.endswith('/index') and virtual not in repos:
                 subdir = virtual[:-len('index')]
                 if any(r.startswith(subdir) for r in repos):
-                    req.respond(HTTP_OK, ctype)
-                    return self.makeindex(req, tmpl, subdir)
+                    wsgireq.respond(HTTP_OK, ctype)
+                    return self.makeindex(wsgireq, tmpl, subdir)
 
             def _virtualdirs():
                 # Check the full virtual path, each parent, and the root ('')
@@ -286,11 +286,11 @@
             for virtualrepo in _virtualdirs():
                 real = repos.get(virtualrepo)
                 if real:
-                    req.env['REPO_NAME'] = virtualrepo
+                    wsgireq.env['REPO_NAME'] = virtualrepo
                     try:
                         # ensure caller gets private copy of ui
                         repo = hg.repository(self.ui.copy(), real)
-                        return hgweb_mod.hgweb(repo).run_wsgi(req)
+                        return hgweb_mod.hgweb(repo).run_wsgi(wsgireq)
                     except IOError as inst:
                         msg = encoding.strtolocal(inst.strerror)
                         raise ErrorResponse(HTTP_SERVER_ERROR, msg)
@@ -300,20 +300,20 @@
             # browse subdirectories
             subdir = virtual + '/'
             if [r for r in repos if r.startswith(subdir)]:
-                req.respond(HTTP_OK, ctype)
-                return self.makeindex(req, tmpl, subdir)
+                wsgireq.respond(HTTP_OK, ctype)
+                return self.makeindex(wsgireq, tmpl, subdir)
 
             # prefixes not found
-            req.respond(HTTP_NOT_FOUND, ctype)
+            wsgireq.respond(HTTP_NOT_FOUND, ctype)
             return tmpl("notfound", repo=virtual)
 
         except ErrorResponse as err:
-            req.respond(err, ctype)
+            wsgireq.respond(err, ctype)
             return tmpl('error', error=err.message or '')
         finally:
             tmpl = None
 
-    def makeindex(self, req, tmpl, subdir=""):
+    def makeindex(self, wsgireq, tmpl, subdir=""):
 
         def archivelist(ui, nodeid, url):
             allowed = ui.configlist("web", "allow_archive", untrusted=True)
@@ -369,8 +369,8 @@
 
                 parts = [name]
                 parts.insert(0, '/' + subdir.rstrip('/'))
-                if req.env['SCRIPT_NAME']:
-                    parts.insert(0, req.env['SCRIPT_NAME'])
+                if wsgireq.env['SCRIPT_NAME']:
+                    parts.insert(0, wsgireq.env['SCRIPT_NAME'])
                 url = re.sub(r'/+', '/', '/'.join(parts) + '/')
 
                 # show either a directory entry or a repository
@@ -413,7 +413,7 @@
                 if u.configbool("web", "hidden", untrusted=True):
                     continue
 
-                if not self.read_allowed(u, req):
+                if not self.read_allowed(u, wsgireq):
                     continue
 
                 # update time with local timezone
@@ -465,8 +465,8 @@
         self.refresh()
         sortable = ["name", "description", "contact", "lastchange"]
         sortcolumn, descending = sortdefault
-        if 'sort' in req.form:
-            sortcolumn = req.form['sort'][0]
+        if 'sort' in wsgireq.form:
+            sortcolumn = wsgireq.form['sort'][0]
             descending = sortcolumn.startswith('-')
             if descending:
                 sortcolumn = sortcolumn[1:]
@@ -479,14 +479,14 @@
                 for column in sortable]
 
         self.refresh()
-        self.updatereqenv(req.env)
+        self.updatereqenv(wsgireq.env)
 
         return tmpl("index", entries=entries, subdir=subdir,
                     pathdef=hgweb_mod.makebreadcrumb('/' + subdir, self.prefix),
                     sortcolumn=sortcolumn, descending=descending,
                     **dict(sort))
 
-    def templater(self, req, nonce):
+    def templater(self, wsgireq, nonce):
 
         def motd(**map):
             if self.motd is not None:
@@ -497,14 +497,14 @@
         def config(section, name, default=uimod._unset, untrusted=True):
             return self.ui.config(section, name, default, untrusted)
 
-        self.updatereqenv(req.env)
+        self.updatereqenv(wsgireq.env)
 
-        url = req.env.get('SCRIPT_NAME', '')
+        url = wsgireq.env.get('SCRIPT_NAME', '')
         if not url.endswith('/'):
             url += '/'
 
         vars = {}
-        styles, (style, mapfile) = hgweb_mod.getstyle(req, config,
+        styles, (style, mapfile) = hgweb_mod.getstyle(wsgireq, config,
                                                       self.templatepath)
         if style == styles[0]:
             vars['style'] = style
--- a/mercurial/wireprotoserver.py	Thu Mar 08 09:44:27 2018 -0800
+++ b/mercurial/wireprotoserver.py	Thu Mar 08 15:15:59 2018 -0800
@@ -36,7 +36,7 @@
 SSHV1 = wireprototypes.SSHV1
 SSHV2 = wireprototypes.SSHV2
 
-def decodevaluefromheaders(req, headerprefix):
+def decodevaluefromheaders(wsgireq, headerprefix):
     """Decode a long value from multiple HTTP request headers.
 
     Returns the value as a bytes, not a str.
@@ -45,7 +45,7 @@
     i = 1
     prefix = headerprefix.upper().replace(r'-', r'_')
     while True:
-        v = req.env.get(r'HTTP_%s_%d' % (prefix, i))
+        v = wsgireq.env.get(r'HTTP_%s_%d' % (prefix, i))
         if v is None:
             break
         chunks.append(pycompat.bytesurl(v))
@@ -54,8 +54,8 @@
     return ''.join(chunks)
 
 class httpv1protocolhandler(wireprototypes.baseprotocolhandler):
-    def __init__(self, req, ui, checkperm):
-        self._req = req
+    def __init__(self, wsgireq, ui, checkperm):
+        self._wsgireq = wsgireq
         self._ui = ui
         self._checkperm = checkperm
 
@@ -79,26 +79,26 @@
         return [data[k] for k in keys]
 
     def _args(self):
-        args = util.rapply(pycompat.bytesurl, self._req.form.copy())
-        postlen = int(self._req.env.get(r'HTTP_X_HGARGS_POST', 0))
+        args = util.rapply(pycompat.bytesurl, self._wsgireq.form.copy())
+        postlen = int(self._wsgireq.env.get(r'HTTP_X_HGARGS_POST', 0))
         if postlen:
             args.update(urlreq.parseqs(
-                self._req.read(postlen), keep_blank_values=True))
+                self._wsgireq.read(postlen), keep_blank_values=True))
             return args
 
-        argvalue = decodevaluefromheaders(self._req, r'X-HgArg')
+        argvalue = decodevaluefromheaders(self._wsgireq, r'X-HgArg')
         args.update(urlreq.parseqs(argvalue, keep_blank_values=True))
         return args
 
     def forwardpayload(self, fp):
-        if r'HTTP_CONTENT_LENGTH' in self._req.env:
-            length = int(self._req.env[r'HTTP_CONTENT_LENGTH'])
+        if r'HTTP_CONTENT_LENGTH' in self._wsgireq.env:
+            length = int(self._wsgireq.env[r'HTTP_CONTENT_LENGTH'])
         else:
-            length = int(self._req.env[r'CONTENT_LENGTH'])
+            length = int(self._wsgireq.env[r'CONTENT_LENGTH'])
         # If httppostargs is used, we need to read Content-Length
         # minus the amount that was consumed by args.
-        length -= int(self._req.env.get(r'HTTP_X_HGARGS_POST', 0))
-        for s in util.filechunkiter(self._req, limit=length):
+        length -= int(self._wsgireq.env.get(r'HTTP_X_HGARGS_POST', 0))
+        for s in util.filechunkiter(self._wsgireq, limit=length):
             fp.write(s)
 
     @contextlib.contextmanager
@@ -118,9 +118,9 @@
 
     def client(self):
         return 'remote:%s:%s:%s' % (
-            self._req.env.get('wsgi.url_scheme') or 'http',
-            urlreq.quote(self._req.env.get('REMOTE_HOST', '')),
-            urlreq.quote(self._req.env.get('REMOTE_USER', '')))
+            self._wsgireq.env.get('wsgi.url_scheme') or 'http',
+            urlreq.quote(self._wsgireq.env.get('REMOTE_HOST', '')),
+            urlreq.quote(self._wsgireq.env.get('REMOTE_USER', '')))
 
     def addcapabilities(self, repo, caps):
         caps.append('httpheader=%d' %
@@ -150,7 +150,7 @@
 def iscmd(cmd):
     return cmd in wireproto.commands
 
-def parsehttprequest(rctx, req, query, checkperm):
+def parsehttprequest(rctx, wsgireq, query, checkperm):
     """Parse the HTTP request for a wire protocol request.
 
     If the current request appears to be a wire protocol request, this
@@ -158,17 +158,17 @@
     an ``abstractprotocolserver`` instance suitable for handling the
     request. Otherwise, ``None`` is returned.
 
-    ``req`` is a ``wsgirequest`` instance.
+    ``wsgireq`` is a ``wsgirequest`` instance.
     """
     repo = rctx.repo
 
     # HTTP version 1 wire protocol requests are denoted by a "cmd" query
     # string parameter. If it isn't present, this isn't a wire protocol
     # request.
-    if 'cmd' not in req.form:
+    if 'cmd' not in wsgireq.form:
         return None
 
-    cmd = req.form['cmd'][0]
+    cmd = wsgireq.form['cmd'][0]
 
     # The "cmd" request parameter is used by both the wire protocol and hgweb.
     # While not all wire protocol commands are available for all transports,
@@ -180,24 +180,24 @@
     if not iscmd(cmd):
         return None
 
-    proto = httpv1protocolhandler(req, repo.ui,
-                                  lambda perm: checkperm(rctx, req, perm))
+    proto = httpv1protocolhandler(wsgireq, repo.ui,
+                                  lambda perm: checkperm(rctx, wsgireq, perm))
 
     return {
         'cmd': cmd,
         'proto': proto,
-        'dispatch': lambda: _callhttp(repo, req, proto, cmd),
-        'handleerror': lambda ex: _handlehttperror(ex, req, cmd),
+        'dispatch': lambda: _callhttp(repo, wsgireq, proto, cmd),
+        'handleerror': lambda ex: _handlehttperror(ex, wsgireq, cmd),
     }
 
-def _httpresponsetype(ui, req, prefer_uncompressed):
+def _httpresponsetype(ui, wsgireq, prefer_uncompressed):
     """Determine the appropriate response type and compression settings.
 
     Returns a tuple of (mediatype, compengine, engineopts).
     """
     # Determine the response media type and compression engine based
     # on the request parameters.
-    protocaps = decodevaluefromheaders(req, r'X-HgProto').split(' ')
+    protocaps = decodevaluefromheaders(wsgireq, r'X-HgProto').split(' ')
 
     if '0.2' in protocaps:
         # All clients are expected to support uncompressed data.
@@ -230,7 +230,7 @@
     opts = {'level': ui.configint('server', 'zliblevel')}
     return HGTYPE, util.compengines['zlib'], opts
 
-def _callhttp(repo, req, proto, cmd):
+def _callhttp(repo, wsgireq, proto, cmd):
     def genversion2(gen, engine, engineopts):
         # application/mercurial-0.2 always sends a payload header
         # identifying the compression engine.
@@ -243,9 +243,9 @@
             yield chunk
 
     if not wireproto.commands.commandavailable(cmd, proto):
-        req.respond(HTTP_OK, HGERRTYPE,
-                    body=_('requested wire protocol command is not available '
-                           'over HTTP'))
+        wsgireq.respond(HTTP_OK, HGERRTYPE,
+                        body=_('requested wire protocol command is not '
+                               'available over HTTP'))
         return []
 
     proto.checkperm(wireproto.commands[cmd].permission)
@@ -253,14 +253,14 @@
     rsp = wireproto.dispatch(repo, proto, cmd)
 
     if isinstance(rsp, bytes):
-        req.respond(HTTP_OK, HGTYPE, body=rsp)
+        wsgireq.respond(HTTP_OK, HGTYPE, body=rsp)
         return []
     elif isinstance(rsp, wireprototypes.bytesresponse):
-        req.respond(HTTP_OK, HGTYPE, body=rsp.data)
+        wsgireq.respond(HTTP_OK, HGTYPE, body=rsp.data)
         return []
     elif isinstance(rsp, wireprototypes.streamreslegacy):
         gen = rsp.gen
-        req.respond(HTTP_OK, HGTYPE)
+        wsgireq.respond(HTTP_OK, HGTYPE)
         return gen
     elif isinstance(rsp, wireprototypes.streamres):
         gen = rsp.gen
@@ -268,32 +268,32 @@
         # This code for compression should not be streamres specific. It
         # is here because we only compress streamres at the moment.
         mediatype, engine, engineopts = _httpresponsetype(
-            repo.ui, req, rsp.prefer_uncompressed)
+            repo.ui, wsgireq, rsp.prefer_uncompressed)
         gen = engine.compressstream(gen, engineopts)
 
         if mediatype == HGTYPE2:
             gen = genversion2(gen, engine, engineopts)
 
-        req.respond(HTTP_OK, mediatype)
+        wsgireq.respond(HTTP_OK, mediatype)
         return gen
     elif isinstance(rsp, wireprototypes.pushres):
         rsp = '%d\n%s' % (rsp.res, rsp.output)
-        req.respond(HTTP_OK, HGTYPE, body=rsp)
+        wsgireq.respond(HTTP_OK, HGTYPE, body=rsp)
         return []
     elif isinstance(rsp, wireprototypes.pusherr):
         # This is the httplib workaround documented in _handlehttperror().
-        req.drain()
+        wsgireq.drain()
 
         rsp = '0\n%s\n' % rsp.res
-        req.respond(HTTP_OK, HGTYPE, body=rsp)
+        wsgireq.respond(HTTP_OK, HGTYPE, body=rsp)
         return []
     elif isinstance(rsp, wireprototypes.ooberror):
         rsp = rsp.message
-        req.respond(HTTP_OK, HGERRTYPE, body=rsp)
+        wsgireq.respond(HTTP_OK, HGERRTYPE, body=rsp)
         return []
     raise error.ProgrammingError('hgweb.protocol internal failure', rsp)
 
-def _handlehttperror(e, req, cmd):
+def _handlehttperror(e, wsgireq, cmd):
     """Called when an ErrorResponse is raised during HTTP request processing."""
 
     # Clients using Python's httplib are stateful: the HTTP client
@@ -304,20 +304,20 @@
     # the HTTP response. In other words, it helps prevent deadlocks
     # on clients using httplib.
 
-    if (req.env[r'REQUEST_METHOD'] == r'POST' and
+    if (wsgireq.env[r'REQUEST_METHOD'] == r'POST' and
         # But not if Expect: 100-continue is being used.
-        (req.env.get('HTTP_EXPECT',
-                     '').lower() != '100-continue') or
+        (wsgireq.env.get('HTTP_EXPECT',
+                         '').lower() != '100-continue') or
         # Or the non-httplib HTTP library is being advertised by
         # the client.
-        req.env.get('X-HgHttp2', '')):
-        req.drain()
+        wsgireq.env.get('X-HgHttp2', '')):
+        wsgireq.drain()
     else:
-        req.headers.append((r'Connection', r'Close'))
+        wsgireq.headers.append((r'Connection', r'Close'))
 
     # TODO This response body assumes the failed command was
     # "unbundle." That assumption is not always valid.
-    req.respond(e, HGTYPE, body='0\n%s\n' % pycompat.bytestr(e))
+    wsgireq.respond(e, HGTYPE, body='0\n%s\n' % pycompat.bytestr(e))
 
     return ''