requirements-dev: add sphinx packaging tools
[git-cola.git] / cola / compat.py
blob4c8c01910d1f5911290f4091abc77db237baa1dd
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:
23 def bstr(x, encoding=ENCODING):
24 return bytes(x, encoding=encoding)
26 elif PY26_PLUS:
27 bstr = bytes
28 else:
29 # Python <= 2.5
30 bstr = str
33 if PY3:
34 def bchr(i):
35 return bytes([i])
37 int_types = (int,)
38 maxsize = sys.maxsize
39 ustr = str
40 uchr = chr
41 else:
42 bchr = chr
43 maxsize = 2 ** 31
44 # pylint: disable=unicode-builtin
45 ustr = unicode # noqa
46 # pylint: disable=unichr-builtin
47 uchr = unichr # noqa
48 # pylint: disable=long-builtin
49 int_types = (int, long) # noqa
51 # Qt's max 32-bit signed integer range (-2147483648 to 2147483647)
52 maxint = (2 ** 31) - 1
55 def setenv(key, value):
56 """Compatibility wrapper for setting environment variables
58 Why? win32 requires putenv(). UNIX only requires os.environ.
59 """
60 if not PY3 and isinstance(value, ustr):
61 value = value.encode(ENCODING, 'replace')
62 os.environ[key] = value
63 os.putenv(key, value)
66 def unsetenv(key):
67 """Compatibility wrapper for unsetting environment variables"""
68 os.environ.pop(key, None)
69 if hasattr(os, 'unsetenv'):
70 os.unsetenv(key)
73 def no_op(value):
74 """Return the value as-is"""
75 return value
78 def byte_offset_to_int_converter():
79 """Return a function to convert byte string offsets into ints
81 Indexing into python3 bytes returns ints, Python2 returns str.
82 Thus, on Python2 we need to use `ord()` to convert the byte into
83 an integer. It's already an int on Python3, so we use no_op there.
84 """
85 if PY2:
86 result = ord
87 else:
88 result = no_op
89 return result