core: add decode_seq() helper
[git-cola.git] / cola / compat.py
blob2873f6202d91571eeefecd08a9ba5d7079139cef
1 # pylint: disable=unused-import,redefined-builtin,undefined-variable
2 from __future__ import absolute_import, division, print_function, unicode_literals
3 import os
4 import sys
6 try:
7 import urllib2 as parse # noqa
8 except ImportError:
9 # Python 3
10 from urllib import parse # noqa
13 PY_VERSION = sys.version_info[:2] # (2, 7)
14 PY_VERSION_MAJOR = PY_VERSION[0]
15 PY2 = PY_VERSION_MAJOR == 2
16 PY3 = PY_VERSION_MAJOR >= 3
17 PY26_PLUS = PY2 and sys.version_info[1] >= 6
18 WIN32 = sys.platform == 'win32' or sys.platform == 'cygwin'
19 ENCODING = 'utf-8'
22 if PY3:
24 def bstr(x, encoding=ENCODING):
25 return bytes(x, encoding=encoding)
28 elif PY26_PLUS:
29 bstr = bytes
30 else:
31 # Python <= 2.5
32 bstr = str
35 if PY3:
37 def bchr(i):
38 return bytes([i])
40 int_types = (int,)
41 maxsize = sys.maxsize
42 ustr = str
43 uchr = chr
44 else:
45 bchr = chr
46 maxsize = 2 ** 31
47 # pylint: disable=unicode-builtin
48 ustr = unicode # noqa
49 # pylint: disable=unichr-builtin
50 uchr = unichr # noqa
51 # pylint: disable=long-builtin
52 int_types = (int, long) # noqa
54 # Qt's max 32-bit signed integer range (-2147483648 to 2147483647)
55 maxint = (2 ** 31) - 1
58 def setenv(key, value):
59 """Compatibility wrapper for setting environment variables
61 Why? win32 requires putenv(). UNIX only requires os.environ.
62 """
63 if not PY3 and isinstance(value, ustr):
64 value = value.encode(ENCODING, 'replace')
65 os.environ[key] = value
66 os.putenv(key, value)
69 def unsetenv(key):
70 """Compatibility wrapper for unsetting environment variables"""
71 os.environ.pop(key, None)
72 if hasattr(os, 'unsetenv'):
73 os.unsetenv(key)
76 def no_op(value):
77 """Return the value as-is"""
78 return value
81 def byte_offset_to_int_converter():
82 """Return a function to convert byte string offsets into ints
84 Indexing into python3 bytes returns ints, Python2 returns str.
85 Thus, on Python2 we need to use `ord()` to convert the byte into
86 an integer. It's already an int on Python3, so we use no_op there.
87 """
88 if PY2:
89 result = ord
90 else:
91 result = no_op
92 return result