Merge pull request #1387 from davvid/remote-dialog
[git-cola.git] / cola / compat.py
blob3d52d3c91005d55c6ae9da632c0fab04f9010b1c
1 import os
2 import sys
4 try:
5 import urllib2 as parse # noqa
6 except ImportError:
7 # Python 3
8 from urllib import parse # noqa
11 PY_VERSION = sys.version_info[:2] # (2, 7)
12 PY_VERSION_MAJOR = PY_VERSION[0]
13 PY2 = PY_VERSION_MAJOR == 2
14 PY3 = PY_VERSION_MAJOR >= 3
15 PY26_PLUS = PY2 and sys.version_info[1] >= 6
16 WIN32 = sys.platform in {'win32', 'cygwin'}
17 ENCODING = 'utf-8'
20 if PY3:
22 def bstr(value, encoding=ENCODING):
23 return bytes(value, encoding=encoding)
25 elif PY26_PLUS:
26 bstr = bytes
27 else:
28 # Python <= 2.5
29 bstr = str
32 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 ustr = unicode # noqa
45 uchr = unichr # noqa
46 int_types = (int, long) # noqa
48 # The max 32-bit signed integer range for Qt is (-2147483648 to 2147483647)
49 maxint = (2**31) - 1
52 def setenv(key, value):
53 """Compatibility wrapper for setting environment variables
55 Windows requires putenv(). Unix only requires os.environ.
56 """
57 if not PY3 and isinstance(value, ustr):
58 value = value.encode(ENCODING, 'replace')
59 os.environ[key] = value
60 os.putenv(key, value)
63 def unsetenv(key):
64 """Compatibility wrapper for clearing environment variables"""
65 os.environ.pop(key, None)
66 if hasattr(os, 'unsetenv'):
67 os.unsetenv(key)
70 def no_op(value):
71 """Return the value as-is"""
72 return value
75 def byte_offset_to_int_converter():
76 """Return a function to convert byte string offsets into integers
78 Indexing into python3 bytes returns integers. Python2 returns str.
79 Thus, on Python2 we need to use `ord()` to convert the byte into
80 an integer. It's already an int on Python3, so we use no_op there.
81 """
82 if PY2:
83 result = ord
84 else:
85 result = no_op
86 return result