##// END OF EJS Templates
Added signature for changeset 5bd6bcd31dd1
Added signature for changeset 5bd6bcd31dd1

File last commit:

r49851:e45c3927 default
r49872:dd98bd0b stable
Show More
pycompat.py
543 lines | 16.3 KiB | text/x-python | PythonLexer
timeless
pycompat: add empty and queue to handle py3 divergence...
r28818 # pycompat.py - portability shim for python 3
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
"""Mercurial portability shim for python 3.
This contains aliases to hide python version-specific details from the core.
"""
from __future__ import absolute_import
Pulkit Goyal
py3: make a bytes version of getopt.getopt()...
r30578 import getopt
Augie Fackler
py3: introduce and use pycompat.getargspec...
r36196 import inspect
Gregory Szorc
py3: define and use json.loads polyfill...
r43697 import json
Pulkit Goyal
py3: add a bytes version of os.name...
r30302 import os
Pulkit Goyal
py3: have a bytes version of shlex.split()...
r30678 import shlex
Pulkit Goyal
pycompat: make pycompat demandimport friendly...
r29584 import sys
Yuya Nishihara
py3: wrap tempfile.mkstemp() to use bytes path...
r38182 import tempfile
Pulkit Goyal
pycompat: make pycompat demandimport friendly...
r29584
Augie Fackler
formatting: blacken the codebase...
r43346 ispy3 = sys.version_info[0] >= 3
Augie Fackler
cleanup: remove pointless r-prefixes on single-quoted strings...
r43906 ispypy = '__pypy__' in sys.builtin_module_names
Yuya Nishihara
typing: consolidate "if not globals():" trick...
r44212 TYPE_CHECKING = False
if not globals(): # hide this from non-pytype users
import typing
TYPE_CHECKING = typing.TYPE_CHECKING
Yuya Nishihara
pycompat: provide 'ispy3' constant...
r30030
if not ispy3:
Gregory Szorc
util: make cookielib module available...
r31934 import cookielib
Pulkit Goyal
py3: conditionalize cPickle import by adding in util...
r29324 import cPickle as pickle
Pulkit Goyal
py3: conditionalize httplib import...
r29455 import httplib
Gregory Szorc
pycompat: export queue module instead of symbols in module (API)...
r37863 import Queue as queue
Pulkit Goyal
py3: conditionalize SocketServer import...
r29433 import SocketServer as socketserver
Pulkit Goyal
py3: conditionalize xmlrpclib import...
r29432 import xmlrpclib
Gregory Szorc
pycompat: export a handle on concurrent.futures...
r37646
from .thirdparty.concurrent import futures
Augie Fackler
py3: paper over differences in future exception handling...
r37687
def future_set_exception_info(f, exc_info):
f.set_exception_info(*exc_info)
Augie Fackler
formatting: blacken the codebase...
r43346
template: FileNotFoundError is actually a built in exception...
r48665 # this is close enough for our usage
FileNotFoundError = OSError
Augie Fackler
formatting: blacken the codebase...
r43346
Pulkit Goyal
pycompat: make pycompat demandimport friendly...
r29584 else:
Raphaël Gomès
compat: don't rely on cpython-specific builtins manipulation...
r49119 import builtins
Gregory Szorc
pycompat: export a handle on concurrent.futures...
r37646 import concurrent.futures as futures
Gregory Szorc
pycompat: import correct cookie module on Python 3...
r31942 import http.cookiejar as cookielib
Pulkit Goyal
pycompat: make pycompat demandimport friendly...
r29584 import http.client as httplib
import pickle
Gregory Szorc
pycompat: export queue module instead of symbols in module (API)...
r37863 import queue as queue
Pulkit Goyal
pycompat: make pycompat demandimport friendly...
r29584 import socketserver
Pulkit Goyal
py3: conditionalize xmlrpclib import...
r29432 import xmlrpc.client as xmlrpclib
Pulkit Goyal
py3: conditionalize the urlparse import...
r29431
Augie Fackler
py3: paper over differences in future exception handling...
r37687 def future_set_exception_info(f, exc_info):
f.set_exception(exc_info[0])
Raphaël Gomès
compat: don't rely on cpython-specific builtins manipulation...
r49119 FileNotFoundError = builtins.FileNotFoundError
template: FileNotFoundError is actually a built in exception...
r48665
Augie Fackler
formatting: blacken the codebase...
r43346
Yuya Nishihara
pycompat: introduce identity function as a compat stub...
r31774 def identity(a):
return a
Augie Fackler
formatting: blacken the codebase...
r43346
Yuya Nishihara
pycompat: move rapply() from util...
r38594 def _rapply(f, xs):
if xs is None:
# assume None means non-value of optional data
return xs
if isinstance(xs, (list, set, tuple)):
return type(xs)(_rapply(f, x) for x in xs)
if isinstance(xs, dict):
return type(xs)((_rapply(f, k), _rapply(f, v)) for k, v in xs.items())
return f(xs)
Augie Fackler
formatting: blacken the codebase...
r43346
Yuya Nishihara
pycompat: move rapply() from util...
r38594 def rapply(f, xs):
"""Apply function recursively to every item preserving the data structure
>>> def f(x):
... return 'f(%s)' % x
>>> rapply(f, None) is None
True
>>> rapply(f, 'a')
'f(a)'
>>> rapply(f, {'a'}) == {'f(a)'}
True
>>> rapply(f, ['a', 'b', None, {'c': 'd'}, []])
['f(a)', 'f(b)', None, {'f(c)': 'f(d)'}, []]
>>> xs = [object()]
>>> rapply(identity, xs) is xs
True
"""
if f is identity:
# fast path mainly for py2
return xs
return _rapply(f, xs)
Augie Fackler
formatting: blacken the codebase...
r43346
Yuya Nishihara
pycompat: provide 'ispy3' constant...
r30030 if ispy3:
Yuya Nishihara
py3: move xrange alias next to import lines...
r29797 import builtins
Gregory Szorc
py3: define and use json.loads polyfill...
r43697 import codecs
Yuya Nishihara
py3: provide (del|get|has|set)attr wrappers that accepts bytes...
r29799 import functools
Yuya Nishihara
pycompat: move imports of cStringIO/io to where they are used...
r31372 import io
Martin von Zweigbergk
py3: optimize py3 compat.bytechr using Struct.pack...
r31424 import struct
Yuya Nishihara
pycompat: move imports of cStringIO/io to where they are used...
r31372
Yuya Nishihara
py3: enable legacy fs encoding to fix filename compatibility on Windows...
r43613 if os.name == r'nt' and sys.version_info >= (3, 6):
# MBCS (or ANSI) filesystem encoding must be used as before.
# Otherwise non-ASCII filenames in existing repositories would be
# corrupted.
# This must be set once prior to any fsencode/fsdecode calls.
Matt Harbison
windows: suppress pytype warnings for Windows imports and functions...
r44207 sys._enablelegacywindowsfsencoding() # pytype: disable=module-attr
Yuya Nishihara
py3: enable legacy fs encoding to fix filename compatibility on Windows...
r43613
Martijn Pieters
py3: add an os.fsencode backport to ease path handling
r30119 fsencode = os.fsencode
Pulkit Goyal
py3: add os.fsdecode() as pycompat.fsdecode()...
r30300 fsdecode = os.fsdecode
Yuya Nishihara
py3: make os.curdir a bytes
r36666 oscurdir = os.curdir.encode('ascii')
Yuya Nishihara
pycompat: provide bytes os.linesep
r31775 oslinesep = os.linesep.encode('ascii')
Pulkit Goyal
py3: add a bytes version of os.name...
r30302 osname = os.name.encode('ascii')
Pulkit Goyal
py3: have pycompat.ospathsep and pycompat.ossep...
r30303 ospathsep = os.pathsep.encode('ascii')
Yuya Nishihara
py3: make os.pardir a bytes
r36665 ospardir = os.pardir.encode('ascii')
Pulkit Goyal
py3: have pycompat.ospathsep and pycompat.ossep...
r30303 ossep = os.sep.encode('ascii')
Pulkit Goyal
py3: have a bytes version of os.altsep...
r30623 osaltsep = os.altsep
if osaltsep:
osaltsep = osaltsep.encode('ascii')
Kyle Lippincott
py3: make a pycompat.osdevnull, use it in extdiff...
r44229 osdevnull = os.devnull.encode('ascii')
Matt Harbison
py3: rename pycompat.getcwd() to encoding.getcwd() (API)...
r39843
Pulkit Goyal
py3: have a bytes version of sys.platform...
r30624 sysplatform = sys.platform.encode('ascii')
Pulkit Goyal
py3: have bytes version of sys.executable...
r30668 sysexecutable = sys.executable
if sysexecutable:
sysexecutable = os.fsencode(sysexecutable)
Gregory Szorc
util: prefer "bytesio" to "stringio"...
r36976 bytesio = io.BytesIO
# TODO deprecate stringio name, as it is a lie on Python 3.
stringio = bytesio
Yuya Nishihara
pycompat: name maplist() and ziplist() for better traceback message
r36952
def maplist(*args):
return list(map(*args))
Yuya Nishihara
annotate: do not construct attr.s object per line while computing history...
r37082 def rangelist(*args):
return list(range(*args))
Yuya Nishihara
pycompat: name maplist() and ziplist() for better traceback message
r36952 def ziplist(*args):
return list(zip(*args))
Yuya Nishihara
py3: select input or raw_input by pycompat...
r33853 rawinput = input
Augie Fackler
py3: introduce and use pycompat.getargspec...
r36196 getargspec = inspect.getfullargspec
Yuya Nishihara
py3: document why os.fsencode() can be used to get back bytes argv...
r30334
Matt Harbison
cbor: teach the encoder to handle python `long` type for Windows...
r39490 long = int
Augie Fackler
pycompat: verify sys.argv exists before forwarding it (issue5493)...
r31277 if getattr(sys, 'argv', None) is not None:
Gregory Szorc
pycompat: change argv conversion semantics...
r45139 # On POSIX, the char** argv array is converted to Python str using
Manuel Jacob
pycompat: use os.fsencode() to re-encode sys.argv...
r45533 # Py_DecodeLocale(). The inverse of this is Py_EncodeLocale(), which
# isn't directly callable from Python code. In practice, os.fsencode()
# can be used instead (this is recommended by Python's documentation
# for sys.argv).
Gregory Szorc
pycompat: change argv conversion semantics...
r45139 #
# On Windows, the wchar_t **argv is passed into the interpreter as-is.
# Like POSIX, we need to emulate what Py_EncodeLocale() would do. But
# there's an additional wrinkle. What we really want to access is the
# ANSI codepage representation of the arguments, as this is what
# `int main()` would receive if Python 3 didn't define `int wmain()`
# (this is how Python 2 worked). To get that, we encode with the mbcs
# encoding, which will pass CP_ACP to the underlying Windows API to
# produce bytes.
if os.name == r'nt':
sysargv = [a.encode("mbcs", "ignore") for a in sys.argv]
else:
Manuel Jacob
pycompat: use os.fsencode() to re-encode sys.argv...
r45533 sysargv = [fsencode(a) for a in sys.argv]
Yuya Nishihara
py3: move xrange alias next to import lines...
r29797
Augie Fackler
cleanup: remove pointless r-prefixes on single-quoted strings...
r43906 bytechr = struct.Struct('>B').pack
Yuya Nishihara
py3: factor out byterepr() which returns an asciified value on py3
r36279 byterepr = b'%r'.__mod__
Yuya Nishihara
py3: factor out bytechr() function...
r31253
Yuya Nishihara
pycompat: add bytestr wrapper which mostly acts as a Python 2 str...
r31439 class bytestr(bytes):
"""A bytes which mostly acts as a Python 2 str
>>> bytestr(), bytestr(bytearray(b'foo')), bytestr(u'ascii'), bytestr(1)
Yuya Nishihara
py3: always drop b'' prefix from repr() of bytestr...
r35921 ('', 'foo', 'ascii', '1')
Yuya Nishihara
pycompat: add bytestr wrapper which mostly acts as a Python 2 str...
r31439 >>> s = bytestr(b'foo')
>>> assert s is bytestr(s)
Yuya Nishihara
pycompat: try __bytes__() to convert object to bytestr...
r32450 __bytes__() should be called if provided:
>>> class bytesable(object):
... def __bytes__(self):
... return b'bytes'
>>> bytestr(bytesable())
Yuya Nishihara
py3: always drop b'' prefix from repr() of bytestr...
r35921 'bytes'
Yuya Nishihara
pycompat: try __bytes__() to convert object to bytestr...
r32450
Yuya Nishihara
pycompat: add bytestr wrapper which mostly acts as a Python 2 str...
r31439 There's no implicit conversion from non-ascii str as its encoding is
unknown:
>>> bytestr(chr(0x80)) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
UnicodeEncodeError: ...
Comparison between bytestr and bytes should work:
>>> assert bytestr(b'foo') == b'foo'
>>> assert b'foo' == bytestr(b'foo')
>>> assert b'f' in bytestr(b'foo')
>>> assert bytestr(b'f') in b'foo'
Sliced elements should be bytes, not integer:
>>> s[1], s[:2]
(b'o', b'fo')
>>> list(s), list(reversed(s))
([b'f', b'o', b'o'], [b'o', b'o', b'f'])
As bytestr type isn't propagated across operations, you need to cast
bytes to bytestr explicitly:
>>> s = bytestr(b'foo').upper()
>>> t = bytestr(s)
>>> s[0], t[0]
(70, b'F')
Be careful to not pass a bytestr object to a function which expects
bytearray-like behavior.
>>> t = bytes(t) # cast to bytes
>>> assert type(t) is bytes
"""
Matt Harbison
typing: add a fake `__init__()` to bytestr to distract pytype...
r48819 # Trick pytype into not demanding Iterable[int] be passed to __new__(),
# since the appropriate bytes format is done internally.
#
# https://github.com/google/pytype/issues/500
if TYPE_CHECKING:
def __init__(self, s=b''):
pass
Yuya Nishihara
pycompat: add bytestr wrapper which mostly acts as a Python 2 str...
r31439 def __new__(cls, s=b''):
if isinstance(s, bytestr):
return s
Augie Fackler
formatting: blacken the codebase...
r43346 if not isinstance(
s, (bytes, bytearray)
) and not hasattr( # hasattr-py3-only
s, u'__bytes__'
):
Gregory Szorc
py3: stop normalizing .encode()/.decode() arguments to unicode...
r43361 s = str(s).encode('ascii')
Yuya Nishihara
pycompat: add bytestr wrapper which mostly acts as a Python 2 str...
r31439 return bytes.__new__(cls, s)
def __getitem__(self, key):
s = bytes.__getitem__(self, key)
if not isinstance(s, bytes):
s = bytechr(s)
return s
def __iter__(self):
return iterbytestr(bytes.__iter__(self))
Yuya Nishihara
py3: always drop b'' prefix from repr() of bytestr...
r35921 def __repr__(self):
return bytes.__repr__(self)[1:] # drop b''
Yuya Nishihara
pycompat: add helper to iterate each char in bytes
r31382 def iterbytestr(s):
"""Iterate bytes as if it were a str object of Python 2"""
Martin von Zweigbergk
py3: make py3 compat.iterbytestr simpler and faster...
r31425 return map(bytechr, s)
Yuya Nishihara
pycompat: add helper to iterate each char in bytes
r31382
Yuya Nishihara
py3: drop b'' from repr() of smartset...
r35922 def maybebytestr(s):
"""Promote bytes to bytestr"""
if isinstance(s, bytes):
return bytestr(s)
return s
Yuya Nishihara
py3: have registrar process docstrings in bytes...
r31820 def sysbytes(s):
"""Convert an internal str (e.g. keyword, __doc__) back to bytes
This never raises UnicodeEncodeError, but only ASCII characters
can be round-trip by sysstr(sysbytes(s)).
"""
Martin von Zweigbergk
pycompat: allow pycompat.sysbytes() even if input already is bytes...
r44322 if isinstance(s, bytes):
return s
Gregory Szorc
py3: stop normalizing .encode()/.decode() arguments to unicode...
r43361 return s.encode('utf-8')
Yuya Nishihara
py3: have registrar process docstrings in bytes...
r31820
Yuya Nishihara
pycompat: extract function that converts attribute or encoding name to str...
r30032 def sysstr(s):
"""Return a keyword str to be passed to Python functions such as
getattr() and str.encode()
This never raises UnicodeDecodeError. Non-ascii characters are
considered invalid and mapped to arbitrary but unique code points
such that 'sysstr(a) != sysstr(b)' for all 'a != b'.
"""
if isinstance(s, builtins.str):
return s
Gregory Szorc
py3: stop normalizing .encode()/.decode() arguments to unicode...
r43361 return s.decode('latin-1')
Yuya Nishihara
pycompat: extract function that converts attribute or encoding name to str...
r30032
Pulkit Goyal
py3: add a new strurl() which will convert a bytes url to str
r32859 def strurl(url):
"""Converts a bytes url back to str"""
Pulkit Goyal
pycompat: prevent encoding or decoding values if not required...
r36662 if isinstance(url, bytes):
Gregory Szorc
py3: stop normalizing .encode()/.decode() arguments to unicode...
r43361 return url.decode('ascii')
Pulkit Goyal
pycompat: prevent encoding or decoding values if not required...
r36662 return url
Pulkit Goyal
py3: add a new strurl() which will convert a bytes url to str
r32859
Pulkit Goyal
py3: add a new bytesurl() to convert a str url into bytes
r32860 def bytesurl(url):
"""Converts a str url to bytes by encoding in ascii"""
Pulkit Goyal
pycompat: prevent encoding or decoding values if not required...
r36662 if isinstance(url, str):
Gregory Szorc
py3: stop normalizing .encode()/.decode() arguments to unicode...
r43361 return url.encode('ascii')
Pulkit Goyal
pycompat: prevent encoding or decoding values if not required...
r36662 return url
Pulkit Goyal
py3: add a new bytesurl() to convert a str url into bytes
r32860
Yuya Nishihara
pycompat: extract helper to raise exception with traceback...
r32186 def raisewithtb(exc, tb):
"""Raise exception with the given traceback"""
raise exc.with_traceback(tb)
Yuya Nishihara
py3: convert __doc__ back to bytes in help.py...
r32615 def getdoc(obj):
"""Get docstring as bytes; may be None so gettext() won't confuse it
with _('')"""
Gregory Szorc
py3: stop normalizing 2nd argument of *attr() to unicode...
r43373 doc = getattr(obj, '__doc__', None)
Yuya Nishihara
py3: convert __doc__ back to bytes in help.py...
r32615 if doc is None:
return doc
return sysbytes(doc)
Yuya Nishihara
py3: provide (del|get|has|set)attr wrappers that accepts bytes...
r29799 def _wrapattrfunc(f):
@functools.wraps(f)
def w(object, name, *args):
Yuya Nishihara
pycompat: extract function that converts attribute or encoding name to str...
r30032 return f(object, sysstr(name), *args)
Augie Fackler
formatting: blacken the codebase...
r43346
Yuya Nishihara
py3: provide (del|get|has|set)attr wrappers that accepts bytes...
r29799 return w
Yuya Nishihara
py3: import builtin wrappers automagically by code transformer...
r29800 # these wrappers are automagically imported by hgloader
Yuya Nishihara
py3: provide (del|get|has|set)attr wrappers that accepts bytes...
r29799 delattr = _wrapattrfunc(builtins.delattr)
getattr = _wrapattrfunc(builtins.getattr)
hasattr = _wrapattrfunc(builtins.hasattr)
setattr = _wrapattrfunc(builtins.setattr)
Yuya Nishihara
py3: import builtin wrappers automagically by code transformer...
r29800 xrange = builtins.range
Pulkit Goyal
py3: add pycompat.unicode and add it to importer...
r31843 unicode = str
Yuya Nishihara
py3: provide (del|get|has|set)attr wrappers that accepts bytes...
r29799
Matt Harbison
py3: byteify strings in pycompat...
r39678 def open(name, mode=b'r', buffering=-1, encoding=None):
Augie Fackler
pycompat: add support for encoding argument to our wrapper...
r36574 return builtins.open(name, sysstr(mode), buffering, encoding)
Pulkit Goyal
py3: add pycompat.open and replace open() calls...
r31149
Yuya Nishihara
util: make safehasattr() a pycompat function...
r37117 safehasattr = _wrapattrfunc(builtins.hasattr)
Yuya Nishihara
fancyopts: use getopt.gnu_getopt()...
r35226 def _getoptbwrapper(orig, args, shortlist, namelist):
Pulkit Goyal
pycompat: move multiline comments above a function to function doc...
r32864 """
Takes bytes arguments, converts them to unicode, pass them to
getopt.getopt(), convert the returned values back to bytes and then
return them for Python 3 compatibility as getopt.getopt() don't accepts
bytes on Python 3.
"""
Pulkit Goyal
py3: make a bytes version of getopt.getopt()...
r30578 args = [a.decode('latin-1') for a in args]
shortlist = shortlist.decode('latin-1')
namelist = [a.decode('latin-1') for a in namelist]
Yuya Nishihara
fancyopts: use getopt.gnu_getopt()...
r35226 opts, args = orig(args, shortlist, namelist)
Augie Fackler
formatting: blacken the codebase...
r43346 opts = [(a[0].encode('latin-1'), a[1].encode('latin-1')) for a in opts]
Pulkit Goyal
py3: make a bytes version of getopt.getopt()...
r30578 args = [a.encode('latin-1') for a in args]
return opts, args
Pulkit Goyal
py3: utility functions to convert keys of kwargs to bytes/unicodes...
r30579 def strkwargs(dic):
Pulkit Goyal
pycompat: move multiline comments above a function to function doc...
r32864 """
Converts the keys of a python dictonary to str i.e. unicodes so that
Joerg Sonnenberger
pycompat: fix typos...
r46794 they can be passed as keyword arguments as dictionaries with bytes keys
Pulkit Goyal
pycompat: move multiline comments above a function to function doc...
r32864 can't be passed as keyword arguments to functions on Python 3.
"""
Augie Fackler
cleanup: run pyupgrade on our source tree to clean up varying things...
r44937 dic = {k.decode('latin-1'): v for k, v in dic.items()}
Pulkit Goyal
py3: utility functions to convert keys of kwargs to bytes/unicodes...
r30579 return dic
def byteskwargs(dic):
Pulkit Goyal
pycompat: move multiline comments above a function to function doc...
r32864 """
Joerg Sonnenberger
pycompat: fix typos...
r46794 Converts keys of python dictionaries to bytes as they were converted to
Pulkit Goyal
pycompat: move multiline comments above a function to function doc...
r32864 str to pass that dictonary as a keyword argument on Python 3.
"""
Augie Fackler
cleanup: run pyupgrade on our source tree to clean up varying things...
r44937 dic = {k.encode('latin-1'): v for k, v in dic.items()}
Pulkit Goyal
py3: utility functions to convert keys of kwargs to bytes/unicodes...
r30579 return dic
Pulkit Goyal
py3: have a bytes version of shlex.split()...
r30678 # TODO: handle shlex.shlex().
Matt Harbison
pycompat: correct the shlex.split() proxy method signature in py3
r36352 def shlexsplit(s, comments=False, posix=True):
Pulkit Goyal
pycompat: move multiline comments above a function to function doc...
r32864 """
Takes bytes argument, convert it to str i.e. unicodes, pass that into
shlex.split(), convert the returned value to bytes and return that for
Python 3 compatibility as shelx.split() don't accept bytes on Python 3.
"""
Matt Harbison
pycompat: correct the shlex.split() proxy method signature in py3
r36352 ret = shlex.split(s.decode('latin-1'), comments, posix)
Pulkit Goyal
py3: have a bytes version of shlex.split()...
r30678 return [a.encode('latin-1') for a in ret]
Gregory Szorc
py3: define and use pycompat.iteritems() for hgext/...
r43375 iteritems = lambda x: x.items()
Gregory Szorc
py3: define and use pycompat.itervalues()...
r43374 itervalues = lambda x: x.values()
Floris Bruynooghe
patchbomb: protect email addresses from shell...
r43289
Gregory Szorc
py3: define and use json.loads polyfill...
r43697 # Python 3.5's json.load and json.loads require str. We polyfill its
# code for detecting encoding from bytes.
if sys.version_info[0:2] < (3, 6):
def _detect_encoding(b):
bstartswith = b.startswith
if bstartswith((codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE)):
return 'utf-32'
if bstartswith((codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE)):
return 'utf-16'
if bstartswith(codecs.BOM_UTF8):
return 'utf-8-sig'
if len(b) >= 4:
if not b[0]:
# 00 00 -- -- - utf-32-be
# 00 XX -- -- - utf-16-be
return 'utf-16-be' if b[1] else 'utf-32-be'
if not b[1]:
# XX 00 00 00 - utf-32-le
# XX 00 00 XX - utf-16-le
# XX 00 XX -- - utf-16-le
return 'utf-16-le' if b[2] or b[3] else 'utf-32-le'
elif len(b) == 2:
if not b[0]:
# 00 XX - utf-16-be
return 'utf-16-be'
if not b[1]:
# XX 00 - utf-16-le
return 'utf-16-le'
# default
return 'utf-8'
def json_loads(s, *args, **kwargs):
if isinstance(s, (bytes, bytearray)):
s = s.decode(_detect_encoding(s), 'surrogatepass')
return json.loads(s, *args, **kwargs)
else:
json_loads = json.loads
Yuya Nishihara
pycompat: extract function that converts attribute or encoding name to str...
r30032 else:
Yuya Nishihara
pycompat: move imports of cStringIO/io to where they are used...
r31372 import cStringIO
Gregory Szorc
pycompat: add xrange alias for Python 2...
r38805 xrange = xrange
Pulkit Goyal
py3: replace `unicode` with pycompat.unicode...
r38332 unicode = unicode
Yuya Nishihara
py3: factor out bytechr() function...
r31253 bytechr = chr
Yuya Nishihara
py3: factor out byterepr() which returns an asciified value on py3
r36279 byterepr = repr
Yuya Nishihara
pycompat: add bytestr wrapper which mostly acts as a Python 2 str...
r31439 bytestr = str
Yuya Nishihara
pycompat: add helper to iterate each char in bytes
r31382 iterbytestr = iter
Yuya Nishihara
py3: drop b'' from repr() of smartset...
r35922 maybebytestr = identity
Yuya Nishihara
py3: have registrar process docstrings in bytes...
r31820 sysbytes = identity
Yuya Nishihara
pycompat: introduce identity function as a compat stub...
r31774 sysstr = identity
Pulkit Goyal
py3: add a new strurl() which will convert a bytes url to str
r32859 strurl = identity
Pulkit Goyal
py3: add a new bytesurl() to convert a str url into bytes
r32860 bytesurl = identity
Gregory Szorc
py3: manually import pycompat.open into files that need it...
r43355 open = open
Gregory Szorc
py3: manually import pycompat.delattr where it is needed...
r43360 delattr = delattr
Gregory Szorc
py3: manually import getattr where it is needed...
r43359 getattr = getattr
Gregory Szorc
py3: stop injecting pycompat.hasattr into modules...
r43358 hasattr = hasattr
Gregory Szorc
py3: manually import pycompat.setattr where it is needed...
r43357 setattr = setattr
Yuya Nishihara
pycompat: extract function that converts attribute or encoding name to str...
r30032
Yuya Nishihara
pycompat: extract helper to raise exception with traceback...
r32186 # this can't be parsed on Python 3
Martin von Zweigbergk
cleanup: join string literals that are already on one line...
r43387 exec(b'def raisewithtb(exc, tb):\n raise exc, None, tb\n')
Yuya Nishihara
pycompat: extract helper to raise exception with traceback...
r32186
Martijn Pieters
pycompat: only accept a bytestring filepath in Python 2
r30133 def fsencode(filename):
Pulkit Goyal
pycompat: move multiline comments above a function to function doc...
r32864 """
Partial backport from os.py in Python 3, which only accepts bytes.
In Python 2, our paths should only ever be bytes, a unicode path
indicates a bug.
"""
Martijn Pieters
pycompat: only accept a bytestring filepath in Python 2
r30133 if isinstance(filename, str):
return filename
Martijn Pieters
py3: add an os.fsencode backport to ease path handling
r30119 else:
Augie Fackler
cleanup: remove pointless r-prefixes on double-quoted strings...
r43809 raise TypeError("expect str, not %s" % type(filename).__name__)
Martijn Pieters
py3: add an os.fsencode backport to ease path handling
r30119
Pulkit Goyal
py3: add os.fsdecode() as pycompat.fsdecode()...
r30300 # In Python 2, fsdecode() has a very chance to receive bytes. So it's
# better not to touch Python 2 part as it's already working fine.
Yuya Nishihara
pycompat: introduce identity function as a compat stub...
r31774 fsdecode = identity
Pulkit Goyal
py3: add os.fsdecode() as pycompat.fsdecode()...
r30300
Yuya Nishihara
py3: convert __doc__ back to bytes in help.py...
r32615 def getdoc(obj):
return getattr(obj, '__doc__', None)
Yuya Nishihara
util: make safehasattr() a pycompat function...
r37117 _notset = object()
def safehasattr(thing, attr):
return getattr(thing, attr, _notset) is not _notset
Yuya Nishihara
fancyopts: use getopt.gnu_getopt()...
r35226 def _getoptbwrapper(orig, args, shortlist, namelist):
return orig(args, shortlist, namelist)
Pulkit Goyal
py3: make a bytes version of getopt.getopt()...
r30578
Yuya Nishihara
pycompat: introduce identity function as a compat stub...
r31774 strkwargs = identity
byteskwargs = identity
Pulkit Goyal
py3: utility functions to convert keys of kwargs to bytes/unicodes...
r30579
Yuya Nishihara
py3: make os.curdir a bytes
r36666 oscurdir = os.curdir
Yuya Nishihara
pycompat: provide bytes os.linesep
r31775 oslinesep = os.linesep
Pulkit Goyal
py3: add a bytes version of os.name...
r30302 osname = os.name
Pulkit Goyal
py3: have pycompat.ospathsep and pycompat.ossep...
r30303 ospathsep = os.pathsep
Yuya Nishihara
py3: make os.pardir a bytes
r36665 ospardir = os.pardir
Pulkit Goyal
py3: have pycompat.ospathsep and pycompat.ossep...
r30303 ossep = os.sep
Pulkit Goyal
py3: have a bytes version of os.altsep...
r30623 osaltsep = os.altsep
Kyle Lippincott
py3: make a pycompat.osdevnull, use it in extdiff...
r44229 osdevnull = os.devnull
Matt Harbison
cbor: teach the encoder to handle python `long` type for Windows...
r39490 long = long
Augie Fackler
pycompat: verify sys.argv exists before forwarding it (issue5493)...
r31277 if getattr(sys, 'argv', None) is not None:
sysargv = sys.argv
Pulkit Goyal
py3: have a bytes version of sys.platform...
r30624 sysplatform = sys.platform
Pulkit Goyal
py3: have bytes version of sys.executable...
r30668 sysexecutable = sys.executable
Pulkit Goyal
py3: have a bytes version of shlex.split()...
r30678 shlexsplit = shlex.split
Gregory Szorc
util: prefer "bytesio" to "stringio"...
r36976 bytesio = cStringIO.StringIO
stringio = bytesio
Augie Fackler
pycompat: add maplist alias for old map behavior
r31501 maplist = map
Yuya Nishihara
annotate: do not construct attr.s object per line while computing history...
r37082 rangelist = range
Pulkit Goyal
py3: introduce pycompat.ziplist as zip is a generator on Python 3...
r35406 ziplist = zip
Yuya Nishihara
py3: select input or raw_input by pycompat...
r33853 rawinput = raw_input
Augie Fackler
py3: introduce and use pycompat.getargspec...
r36196 getargspec = inspect.getargspec
Gregory Szorc
py3: define and use pycompat.iteritems() for hgext/...
r43375 iteritems = lambda x: x.iteritems()
Gregory Szorc
py3: define and use pycompat.itervalues()...
r43374 itervalues = lambda x: x.itervalues()
Gregory Szorc
py3: define and use json.loads polyfill...
r43697 json_loads = json.loads
Jun Wu
selectors2: do not use platform.system()...
r34640
Matt Harbison
py3: byteify strings in pycompat...
r39678 isjython = sysplatform.startswith(b'java')
Jun Wu
pycompat: define operating system constants...
r34645
rdamazio@google.com
pycompat: adding Linux detection and fixing Mac...
r40563 isdarwin = sysplatform.startswith(b'darwin')
islinux = sysplatform.startswith(b'linux')
Matt Harbison
py3: byteify strings in pycompat...
r39678 isposix = osname == b'posix'
iswindows = osname == b'nt'
Yuya Nishihara
fancyopts: use getopt.gnu_getopt()...
r35226
Augie Fackler
formatting: blacken the codebase...
r43346
Yuya Nishihara
fancyopts: use getopt.gnu_getopt()...
r35226 def getoptb(args, shortlist, namelist):
return _getoptbwrapper(getopt.getopt, args, shortlist, namelist)
Augie Fackler
formatting: blacken the codebase...
r43346
Yuya Nishihara
fancyopts: use getopt.gnu_getopt()...
r35226 def gnugetoptb(args, shortlist, namelist):
return _getoptbwrapper(getopt.gnu_getopt, args, shortlist, namelist)
Yuya Nishihara
py3: wrap tempfile.mkstemp() to use bytes path...
r38182
Augie Fackler
formatting: blacken the codebase...
r43346
Yuya Nishihara
py3: wrap tempfile.mkdtemp() to use bytes path...
r38183 def mkdtemp(suffix=b'', prefix=b'tmp', dir=None):
return tempfile.mkdtemp(suffix, prefix, dir)
Augie Fackler
formatting: blacken the codebase...
r43346
Yuya Nishihara
py3: wrap tempfile.mkstemp() to use bytes path...
r38182 # text=True is not supported; use util.from/tonativeeol() instead
def mkstemp(suffix=b'', prefix=b'tmp', dir=None):
return tempfile.mkstemp(suffix, prefix, dir)
Yuya Nishihara
py3: wrap tempfile.NamedTemporaryFile() to return bytes fp.name...
r38184
Augie Fackler
formatting: blacken the codebase...
r43346
pycompat: add an entry for unnamedtmpfile...
r46319 # TemporaryFile does not support an "encoding=" argument on python2.
# This wrapper file are always open in byte mode.
def unnamedtempfile(mode=None, *args, **kwargs):
if mode is None:
Matt Harbison
pycompat: fix a bytes vs str issue in `unnamedtempfile()`...
r47385 mode = 'w+b'
pycompat: add an entry for unnamedtmpfile...
r46319 else:
mode = sysstr(mode)
assert 'b' in mode
return tempfile.TemporaryFile(mode, *args, **kwargs)
pycompat: update comment about unnamedtempfile...
r46318 # NamedTemporaryFile does not support an "encoding=" argument on python2.
# This wrapper file are always open in byte mode.
Augie Fackler
formatting: blacken the codebase...
r43346 def namedtempfile(
mode=b'w+b', bufsize=-1, suffix=b'', prefix=b'tmp', dir=None, delete=True
):
Yuya Nishihara
py3: wrap tempfile.NamedTemporaryFile() to return bytes fp.name...
r38184 mode = sysstr(mode)
Augie Fackler
cleanup: remove pointless r-prefixes on single-quoted strings...
r43906 assert 'b' in mode
Augie Fackler
formatting: blacken the codebase...
r43346 return tempfile.NamedTemporaryFile(
mode, bufsize, suffix=suffix, prefix=prefix, dir=dir, delete=delete
)