mercurial/urllibcompat.py
author Manuel Jacob <me@manueljacob.de>
Mon, 11 Jul 2022 01:51:20 +0200
branchstable
changeset 49378 094a5fa3cf52
parent 48946 642e31cb55f0
child 50929 18c8c18993f0
permissions -rw-r--r--
procutil: make stream detection in make_line_buffered more correct and strict In make_line_buffered(), we don’t want to wrap the stream if we know that lines get flushed to the underlying raw stream already. Previously, the heuristic was too optimistic. It assumed that any stream which is not an instance of io.BufferedIOBase doesn’t need wrapping. However, there are buffered streams that aren’t instances of io.BufferedIOBase, like Mercurial’s own winstdout. The new logic is different in two ways: First, only for the check, if unwraps any combination of WriteAllWrapper and winstdout. Second, it skips wrapping the stream only if it is an instance of io.RawIOBase (or already wrapped). If it is an instance of io.BufferedIOBase, it gets wrapped. In any other case, the function raises an exception. This ensures that, if an unknown stream is passed or we add another wrapper in the future, we don’t wrap the stream if it’s already line buffered or not wrap the stream if it’s not line buffered. In fact, this was already helpful during development of this change. Without it, I possibly would have forgot that WriteAllWrapper needs to be ignored for the check, leading to unnecessary wrapping if stdout is unbuffered. The alternative would have been to always wrap unknown streams. However, I don’t think that anyone would benefit from being less strict. We can expect streams from the standard library to be subclassing either io.RawIOBase or io.BufferedIOBase, so running Mercurial in the standard way should not regress by this change. Py2exe might replace sys.stdout and sys.stderr, but that currently breaks Mercurial anyway and also these streams don’t claim to be interactive, so this function is not called for them.

# urllibcompat.py - adapters to ease using urllib2 on Py2 and urllib on Py3
#
# Copyright 2017 Google, Inc.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.

import http.server
import urllib.error
import urllib.parse
import urllib.request
import urllib.response

from .pycompat import getattr
from . import pycompat

_sysstr = pycompat.sysstr


class _pycompatstub:
    def __init__(self):
        self._aliases = {}

    def _registeraliases(self, origin, items):
        """Add items that will be populated at the first access"""
        items = map(_sysstr, items)
        self._aliases.update(
            (item.replace('_', '').lower(), (origin, item)) for item in items
        )

    def _registeralias(self, origin, attr, name):
        """Alias ``origin``.``attr`` as ``name``"""
        self._aliases[_sysstr(name)] = (origin, _sysstr(attr))

    def __getattr__(self, name):
        try:
            origin, item = self._aliases[name]
        except KeyError:
            raise AttributeError(name)
        self.__dict__[name] = obj = getattr(origin, item)
        return obj


httpserver = _pycompatstub()
urlreq = _pycompatstub()
urlerr = _pycompatstub()

urlreq._registeraliases(
    urllib.parse,
    (
        b"splitattr",
        b"splitpasswd",
        b"splitport",
        b"splituser",
        b"urlparse",
        b"urlunparse",
    ),
)
urlreq._registeralias(urllib.parse, b"parse_qs", b"parseqs")
urlreq._registeralias(urllib.parse, b"parse_qsl", b"parseqsl")
urlreq._registeralias(urllib.parse, b"unquote_to_bytes", b"unquote")

urlreq._registeraliases(
    urllib.request,
    (
        b"AbstractHTTPHandler",
        b"BaseHandler",
        b"build_opener",
        b"FileHandler",
        b"FTPHandler",
        b"ftpwrapper",
        b"HTTPHandler",
        b"HTTPSHandler",
        b"install_opener",
        b"pathname2url",
        b"HTTPBasicAuthHandler",
        b"HTTPDigestAuthHandler",
        b"HTTPPasswordMgrWithDefaultRealm",
        b"ProxyHandler",
        b"Request",
        b"url2pathname",
        b"urlopen",
    ),
)


urlreq._registeraliases(
    urllib.response,
    (
        b"addclosehook",
        b"addinfourl",
    ),
)

urlerr._registeraliases(
    urllib.error,
    (
        b"HTTPError",
        b"URLError",
    ),
)

httpserver._registeraliases(
    http.server,
    (
        b"HTTPServer",
        b"BaseHTTPRequestHandler",
        b"SimpleHTTPRequestHandler",
        b"CGIHTTPRequestHandler",
    ),
)

# urllib.parse.quote() accepts both str and bytes, decodes bytes
# (if necessary), and returns str. This is wonky. We provide a custom
# implementation that only accepts bytes and emits bytes.
def quote(s, safe='/'):
    # bytestr has an __iter__ that emits characters. quote_from_bytes()
    # does an iteration and expects ints. We coerce to bytes to appease it.
    if isinstance(s, pycompat.bytestr):
        s = bytes(s)
    s = urllib.parse.quote_from_bytes(s, safe=safe)
    return s.encode('ascii', 'strict')


# urllib.parse.urlencode() returns str. We use this function to make
# sure we return bytes.
def urlencode(query, doseq=False):
    s = urllib.parse.urlencode(query, doseq=doseq)
    return s.encode('ascii')


urlreq.quote = quote
urlreq.urlencode = urlencode


def getfullurl(req):
    return req.full_url


def gethost(req):
    return req.host


def getselector(req):
    return req.selector


def getdata(req):
    return req.data


def hasdata(req):
    return req.data is not None