widgets.remote: retain focus when showing remote messages
[git-cola.git] / cola / compat.py
blob7060b3e134cb176fa38954cc0e472602ea01e709
1 # pylint: disable=unused-import,redefined-builtin,undefined-variable
2 import os
3 import sys
5 try:
6 import urllib2 as parse # noqa
7 except ImportError:
8 # Python 3
9 from urllib import parse # noqa
12 PY_VERSION = sys.version_info[:2] # (2, 7)
13 PY_VERSION_MAJOR = PY_VERSION[0]
14 PY2 = PY_VERSION_MAJOR == 2
15 PY3 = PY_VERSION_MAJOR >= 3
16 PY26_PLUS = PY2 and sys.version_info[1] >= 6
17 WIN32 = sys.platform in {'win32', 'cygwin'}
18 ENCODING = 'utf-8'
21 if PY3:
23 def bstr(value, encoding=ENCODING):
24 return bytes(value, encoding=encoding)
26 elif PY26_PLUS:
27 bstr = bytes
28 else:
29 # Python <= 2.5
30 bstr = str
33 if PY3:
35 def bchr(i):
36 return bytes([i])
38 int_types = (int,)
39 maxsize = sys.maxsize
40 ustr = str
41 uchr = chr
42 else:
43 bchr = chr
44 maxsize = 2**31
45 ustr = unicode # noqa
46 uchr = unichr # noqa
47 int_types = (int, long) # noqa
49 # Qt's max 32-bit signed integer range (-2147483648 to 2147483647)
50 maxint = (2**31) - 1
53 def setenv(key, value):
54 """Compatibility wrapper for setting environment variables
56 Why? win32 requires putenv(). UNIX only requires os.environ.
57 """
58 if not PY3 and isinstance(value, ustr):
59 value = value.encode(ENCODING, 'replace')
60 os.environ[key] = value
61 os.putenv(key, value)
64 def unsetenv(key):
65 """Compatibility wrapper for unsetting environment variables"""
66 os.environ.pop(key, None)
67 if hasattr(os, 'unsetenv'):
68 os.unsetenv(key)
71 def no_op(value):
72 """Return the value as-is"""
73 return value
76 def byte_offset_to_int_converter():
77 """Return a function to convert byte string offsets into ints
79 Indexing into python3 bytes returns ints, Python2 returns str.
80 Thus, on Python2 we need to use `ord()` to convert the byte into
81 an integer. It's already an int on Python3, so we use no_op there.
82 """
83 if PY2:
84 result = ord
85 else:
86 result = no_op
87 return result