Merge pull request #1000 from bensmrs/master
[git-cola.git] / cola / compat.py
blobdfc5ebfbb8e51a1781822dc243b41dc96366295c
1 # pylint: disable=unused-import,redefined-builtin,undefined-variable
2 from __future__ import absolute_import, division, unicode_literals
3 import os
4 import sys
5 try:
6 import urllib2 as parse # noqa
7 except ImportError:
8 # Python 3
9 from urllib import parse # noqa
12 PY2 = sys.version_info[0] == 2
13 PY3 = sys.version_info[0] >= 3
14 PY26_PLUS = PY2 and sys.version_info[1] >= 6
15 WIN32 = sys.platform == 'win32' or sys.platform == 'cygwin'
16 ENCODING = 'utf-8'
19 if PY3:
20 def bstr(x, encoding=ENCODING):
21 return bytes(x, encoding=encoding)
23 elif PY26_PLUS:
24 bstr = bytes
25 else:
26 # Python <= 2.5
27 bstr = str
29 if PY3:
30 def bchr(i):
31 return bytes([i])
33 int_types = (int,)
34 maxsize = sys.maxsize
35 ustr = str
36 uchr = chr
37 else:
38 bchr = chr
39 maxsize = 2 ** 31
40 # pylint: disable=unicode-builtin
41 ustr = unicode # noqa
42 # pylint: disable=unichr-builtin
43 uchr = unichr # noqa
44 # pylint: disable=long-builtin
45 int_types = (int, long) # noqa
48 def setenv(key, value):
49 """Compatibility wrapper for setting environment variables
51 Why? win32 requires putenv(). UNIX only requires os.environ.
53 """
54 if not PY3 and isinstance(value, ustr):
55 value = value.encode(ENCODING, 'replace')
56 os.environ[key] = value
57 os.putenv(key, value)
60 def unsetenv(key):
61 """Compatibility wrapper for unsetting environment variables"""
62 os.environ.pop(key, None)
63 if hasattr(os, 'unsetenv'):
64 os.unsetenv(key)