git-cola v4.3.1
[git-cola.git] / cola / compat.py
blob290cb517831e76008284006fd73bb39b5bf39679
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 in {'win32', 'cygwin'}
19 ENCODING = 'utf-8'
22 if PY3:
24 def bstr(value, encoding=ENCODING):
25 return bytes(value, encoding=encoding)
27 elif PY26_PLUS:
28 bstr = bytes
29 else:
30 # Python <= 2.5
31 bstr = str
34 if PY3:
36 def bchr(i):
37 return bytes([i])
39 int_types = (int,)
40 maxsize = sys.maxsize
41 ustr = str
42 uchr = chr
43 else:
44 bchr = chr
45 maxsize = 2**31
46 ustr = unicode # noqa
47 uchr = unichr # noqa
48 int_types = (int, long) # noqa
50 # Qt's max 32-bit signed integer range (-2147483648 to 2147483647)
51 maxint = (2**31) - 1
54 def setenv(key, value):
55 """Compatibility wrapper for setting environment variables
57 Why? win32 requires putenv(). UNIX only requires os.environ.
58 """
59 if not PY3 and isinstance(value, ustr):
60 value = value.encode(ENCODING, 'replace')
61 os.environ[key] = value
62 os.putenv(key, value)
65 def unsetenv(key):
66 """Compatibility wrapper for unsetting environment variables"""
67 os.environ.pop(key, None)
68 if hasattr(os, 'unsetenv'):
69 os.unsetenv(key)
72 def no_op(value):
73 """Return the value as-is"""
74 return value
77 def byte_offset_to_int_converter():
78 """Return a function to convert byte string offsets into ints
80 Indexing into python3 bytes returns ints, Python2 returns str.
81 Thus, on Python2 we need to use `ord()` to convert the byte into
82 an integer. It's already an int on Python3, so we use no_op there.
83 """
84 if PY2:
85 result = ord
86 else:
87 result = no_op
88 return result