##// END OF EJS Templates
pycompat: remove large Python 2 block...
Gregory Szorc -
r49726:79009cca default
parent child Browse files
Show More
@@ -11,21 +11,26 b' This contains aliases to hide python ver'
11 from __future__ import absolute_import
11 from __future__ import absolute_import
12
12
13 import builtins
13 import builtins
14 import codecs
14 import concurrent.futures as futures
15 import concurrent.futures as futures
16 import functools
15 import getopt
17 import getopt
16 import http.client as httplib
18 import http.client as httplib
17 import http.cookiejar as cookielib
19 import http.cookiejar as cookielib
18 import inspect
20 import inspect
21 import io
19 import json
22 import json
20 import os
23 import os
21 import pickle
24 import pickle
22 import queue
25 import queue
23 import shlex
26 import shlex
24 import socketserver
27 import socketserver
28 import struct
25 import sys
29 import sys
26 import tempfile
30 import tempfile
27 import xmlrpc.client as xmlrpclib
31 import xmlrpc.client as xmlrpclib
28
32
33
29 ispy3 = sys.version_info[0] >= 3
34 ispy3 = sys.version_info[0] >= 3
30 ispypy = '__pypy__' in sys.builtin_module_names
35 ispypy = '__pypy__' in sys.builtin_module_names
31 TYPE_CHECKING = False
36 TYPE_CHECKING = False
@@ -82,13 +87,6 b' def rapply(f, xs):'
82 return _rapply(f, xs)
87 return _rapply(f, xs)
83
88
84
89
85 if ispy3:
86 import builtins
87 import codecs
88 import functools
89 import io
90 import struct
91
92 if os.name == r'nt' and sys.version_info >= (3, 6):
90 if os.name == r'nt' and sys.version_info >= (3, 6):
93 # MBCS (or ANSI) filesystem encoding must be used as before.
91 # MBCS (or ANSI) filesystem encoding must be used as before.
94 # Otherwise non-ASCII filenames in existing repositories would be
92 # Otherwise non-ASCII filenames in existing repositories would be
@@ -117,15 +115,19 b' if ispy3:'
117 # TODO deprecate stringio name, as it is a lie on Python 3.
115 # TODO deprecate stringio name, as it is a lie on Python 3.
118 stringio = bytesio
116 stringio = bytesio
119
117
118
120 def maplist(*args):
119 def maplist(*args):
121 return list(map(*args))
120 return list(map(*args))
122
121
122
123 def rangelist(*args):
123 def rangelist(*args):
124 return list(range(*args))
124 return list(range(*args))
125
125
126
126 def ziplist(*args):
127 def ziplist(*args):
127 return list(zip(*args))
128 return list(zip(*args))
128
129
130
129 rawinput = input
131 rawinput = input
130 getargspec = inspect.getfullargspec
132 getargspec = inspect.getfullargspec
131
133
@@ -154,6 +156,7 b' if ispy3:'
154 bytechr = struct.Struct('>B').pack
156 bytechr = struct.Struct('>B').pack
155 byterepr = b'%r'.__mod__
157 byterepr = b'%r'.__mod__
156
158
159
157 class bytestr(bytes):
160 class bytestr(bytes):
158 """A bytes which mostly acts as a Python 2 str
161 """A bytes which mostly acts as a Python 2 str
159
162
@@ -239,16 +242,19 b' if ispy3:'
239 def __repr__(self):
242 def __repr__(self):
240 return bytes.__repr__(self)[1:] # drop b''
243 return bytes.__repr__(self)[1:] # drop b''
241
244
245
242 def iterbytestr(s):
246 def iterbytestr(s):
243 """Iterate bytes as if it were a str object of Python 2"""
247 """Iterate bytes as if it were a str object of Python 2"""
244 return map(bytechr, s)
248 return map(bytechr, s)
245
249
250
246 def maybebytestr(s):
251 def maybebytestr(s):
247 """Promote bytes to bytestr"""
252 """Promote bytes to bytestr"""
248 if isinstance(s, bytes):
253 if isinstance(s, bytes):
249 return bytestr(s)
254 return bytestr(s)
250 return s
255 return s
251
256
257
252 def sysbytes(s):
258 def sysbytes(s):
253 """Convert an internal str (e.g. keyword, __doc__) back to bytes
259 """Convert an internal str (e.g. keyword, __doc__) back to bytes
254
260
@@ -259,6 +265,7 b' if ispy3:'
259 return s
265 return s
260 return s.encode('utf-8')
266 return s.encode('utf-8')
261
267
268
262 def sysstr(s):
269 def sysstr(s):
263 """Return a keyword str to be passed to Python functions such as
270 """Return a keyword str to be passed to Python functions such as
264 getattr() and str.encode()
271 getattr() and str.encode()
@@ -271,22 +278,26 b' if ispy3:'
271 return s
278 return s
272 return s.decode('latin-1')
279 return s.decode('latin-1')
273
280
281
274 def strurl(url):
282 def strurl(url):
275 """Converts a bytes url back to str"""
283 """Converts a bytes url back to str"""
276 if isinstance(url, bytes):
284 if isinstance(url, bytes):
277 return url.decode('ascii')
285 return url.decode('ascii')
278 return url
286 return url
279
287
288
280 def bytesurl(url):
289 def bytesurl(url):
281 """Converts a str url to bytes by encoding in ascii"""
290 """Converts a str url to bytes by encoding in ascii"""
282 if isinstance(url, str):
291 if isinstance(url, str):
283 return url.encode('ascii')
292 return url.encode('ascii')
284 return url
293 return url
285
294
295
286 def raisewithtb(exc, tb):
296 def raisewithtb(exc, tb):
287 """Raise exception with the given traceback"""
297 """Raise exception with the given traceback"""
288 raise exc.with_traceback(tb)
298 raise exc.with_traceback(tb)
289
299
300
290 def getdoc(obj):
301 def getdoc(obj):
291 """Get docstring as bytes; may be None so gettext() won't confuse it
302 """Get docstring as bytes; may be None so gettext() won't confuse it
292 with _('')"""
303 with _('')"""
@@ -295,6 +306,7 b' if ispy3:'
295 return doc
306 return doc
296 return sysbytes(doc)
307 return sysbytes(doc)
297
308
309
298 def _wrapattrfunc(f):
310 def _wrapattrfunc(f):
299 @functools.wraps(f)
311 @functools.wraps(f)
300 def w(object, name, *args):
312 def w(object, name, *args):
@@ -302,6 +314,7 b' if ispy3:'
302
314
303 return w
315 return w
304
316
317
305 # these wrappers are automagically imported by hgloader
318 # these wrappers are automagically imported by hgloader
306 delattr = _wrapattrfunc(builtins.delattr)
319 delattr = _wrapattrfunc(builtins.delattr)
307 getattr = _wrapattrfunc(builtins.getattr)
320 getattr = _wrapattrfunc(builtins.getattr)
@@ -310,11 +323,14 b' if ispy3:'
310 xrange = builtins.range
323 xrange = builtins.range
311 unicode = str
324 unicode = str
312
325
326
313 def open(name, mode=b'r', buffering=-1, encoding=None):
327 def open(name, mode=b'r', buffering=-1, encoding=None):
314 return builtins.open(name, sysstr(mode), buffering, encoding)
328 return builtins.open(name, sysstr(mode), buffering, encoding)
315
329
330
316 safehasattr = _wrapattrfunc(builtins.hasattr)
331 safehasattr = _wrapattrfunc(builtins.hasattr)
317
332
333
318 def _getoptbwrapper(orig, args, shortlist, namelist):
334 def _getoptbwrapper(orig, args, shortlist, namelist):
319 """
335 """
320 Takes bytes arguments, converts them to unicode, pass them to
336 Takes bytes arguments, converts them to unicode, pass them to
@@ -330,6 +346,7 b' if ispy3:'
330 args = [a.encode('latin-1') for a in args]
346 args = [a.encode('latin-1') for a in args]
331 return opts, args
347 return opts, args
332
348
349
333 def strkwargs(dic):
350 def strkwargs(dic):
334 """
351 """
335 Converts the keys of a python dictonary to str i.e. unicodes so that
352 Converts the keys of a python dictonary to str i.e. unicodes so that
@@ -339,6 +356,7 b' if ispy3:'
339 dic = {k.decode('latin-1'): v for k, v in dic.items()}
356 dic = {k.decode('latin-1'): v for k, v in dic.items()}
340 return dic
357 return dic
341
358
359
342 def byteskwargs(dic):
360 def byteskwargs(dic):
343 """
361 """
344 Converts keys of python dictionaries to bytes as they were converted to
362 Converts keys of python dictionaries to bytes as they were converted to
@@ -347,6 +365,7 b' if ispy3:'
347 dic = {k.encode('latin-1'): v for k, v in dic.items()}
365 dic = {k.encode('latin-1'): v for k, v in dic.items()}
348 return dic
366 return dic
349
367
368
350 # TODO: handle shlex.shlex().
369 # TODO: handle shlex.shlex().
351 def shlexsplit(s, comments=False, posix=True):
370 def shlexsplit(s, comments=False, posix=True):
352 """
371 """
@@ -357,6 +376,7 b' if ispy3:'
357 ret = shlex.split(s.decode('latin-1'), comments, posix)
376 ret = shlex.split(s.decode('latin-1'), comments, posix)
358 return [a.encode('latin-1') for a in ret]
377 return [a.encode('latin-1') for a in ret]
359
378
379
360 iteritems = lambda x: x.items()
380 iteritems = lambda x: x.items()
361 itervalues = lambda x: x.values()
381 itervalues = lambda x: x.values()
362
382
@@ -399,84 +419,8 b' if ispy3:'
399
419
400 return json.loads(s, *args, **kwargs)
420 return json.loads(s, *args, **kwargs)
401
421
402 else:
403 json_loads = json.loads
404
422
405 else:
423 else:
406 import cStringIO
407
408 xrange = xrange
409 unicode = unicode
410 bytechr = chr
411 byterepr = repr
412 bytestr = str
413 iterbytestr = iter
414 maybebytestr = identity
415 sysbytes = identity
416 sysstr = identity
417 strurl = identity
418 bytesurl = identity
419 open = open
420 delattr = delattr
421 getattr = getattr
422 hasattr = hasattr
423 setattr = setattr
424
425 # this can't be parsed on Python 3
426 exec(b'def raisewithtb(exc, tb):\n raise exc, None, tb\n')
427
428 def fsencode(filename):
429 """
430 Partial backport from os.py in Python 3, which only accepts bytes.
431 In Python 2, our paths should only ever be bytes, a unicode path
432 indicates a bug.
433 """
434 if isinstance(filename, str):
435 return filename
436 else:
437 raise TypeError("expect str, not %s" % type(filename).__name__)
438
439 # In Python 2, fsdecode() has a very chance to receive bytes. So it's
440 # better not to touch Python 2 part as it's already working fine.
441 fsdecode = identity
442
443 def getdoc(obj):
444 return getattr(obj, '__doc__', None)
445
446 _notset = object()
447
448 def safehasattr(thing, attr):
449 return getattr(thing, attr, _notset) is not _notset
450
451 def _getoptbwrapper(orig, args, shortlist, namelist):
452 return orig(args, shortlist, namelist)
453
454 strkwargs = identity
455 byteskwargs = identity
456
457 oscurdir = os.curdir
458 oslinesep = os.linesep
459 osname = os.name
460 ospathsep = os.pathsep
461 ospardir = os.pardir
462 ossep = os.sep
463 osaltsep = os.altsep
464 osdevnull = os.devnull
465 long = long
466 if getattr(sys, 'argv', None) is not None:
467 sysargv = sys.argv
468 sysplatform = sys.platform
469 sysexecutable = sys.executable
470 shlexsplit = shlex.split
471 bytesio = cStringIO.StringIO
472 stringio = bytesio
473 maplist = map
474 rangelist = range
475 ziplist = zip
476 rawinput = raw_input
477 getargspec = inspect.getargspec
478 iteritems = lambda x: x.iteritems()
479 itervalues = lambda x: x.itervalues()
480 json_loads = json.loads
424 json_loads = json.loads
481
425
482 isjython = sysplatform.startswith(b'java')
426 isjython = sysplatform.startswith(b'java')
General Comments 0
You need to be logged in to leave comments. Login now