Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

compat.py 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. """Stuff that differs in different Python versions and platform
  2. distributions."""
  3. from __future__ import absolute_import, division
  4. import codecs
  5. import locale
  6. import logging
  7. import os
  8. import shutil
  9. import sys
  10. from pip._vendor.six import text_type
  11. try:
  12. import ipaddress
  13. except ImportError:
  14. try:
  15. from pip._vendor import ipaddress # type: ignore
  16. except ImportError:
  17. import ipaddr as ipaddress # type: ignore
  18. ipaddress.ip_address = ipaddress.IPAddress
  19. ipaddress.ip_network = ipaddress.IPNetwork
  20. __all__ = [
  21. "ipaddress", "uses_pycache", "console_to_str", "native_str",
  22. "get_path_uid", "stdlib_pkgs", "WINDOWS", "samefile", "get_terminal_size",
  23. "get_extension_suffixes",
  24. ]
  25. logger = logging.getLogger(__name__)
  26. if sys.version_info >= (3, 4):
  27. uses_pycache = True
  28. from importlib.util import cache_from_source
  29. else:
  30. import imp
  31. try:
  32. cache_from_source = imp.cache_from_source # type: ignore
  33. except AttributeError:
  34. # does not use __pycache__
  35. cache_from_source = None
  36. uses_pycache = cache_from_source is not None
  37. if sys.version_info >= (3, 5):
  38. backslashreplace_decode = "backslashreplace"
  39. else:
  40. # In version 3.4 and older, backslashreplace exists
  41. # but does not support use for decoding.
  42. # We implement our own replace handler for this
  43. # situation, so that we can consistently use
  44. # backslash replacement for all versions.
  45. def backslashreplace_decode_fn(err):
  46. raw_bytes = (err.object[i] for i in range(err.start, err.end))
  47. if sys.version_info[0] == 2:
  48. # Python 2 gave us characters - convert to numeric bytes
  49. raw_bytes = (ord(b) for b in raw_bytes)
  50. return u"".join(u"\\x%x" % c for c in raw_bytes), err.end
  51. codecs.register_error(
  52. "backslashreplace_decode",
  53. backslashreplace_decode_fn,
  54. )
  55. backslashreplace_decode = "backslashreplace_decode"
  56. def console_to_str(data):
  57. """Return a string, safe for output, of subprocess output.
  58. We assume the data is in the locale preferred encoding.
  59. If it won't decode properly, we warn the user but decode as
  60. best we can.
  61. We also ensure that the output can be safely written to
  62. standard output without encoding errors.
  63. """
  64. # First, get the encoding we assume. This is the preferred
  65. # encoding for the locale, unless that is not found, or
  66. # it is ASCII, in which case assume UTF-8
  67. encoding = locale.getpreferredencoding()
  68. if (not encoding) or codecs.lookup(encoding).name == "ascii":
  69. encoding = "utf-8"
  70. # Now try to decode the data - if we fail, warn the user and
  71. # decode with replacement.
  72. try:
  73. s = data.decode(encoding)
  74. except UnicodeDecodeError:
  75. logger.warning(
  76. "Subprocess output does not appear to be encoded as %s",
  77. encoding,
  78. )
  79. s = data.decode(encoding, errors=backslashreplace_decode)
  80. # Make sure we can print the output, by encoding it to the output
  81. # encoding with replacement of unencodable characters, and then
  82. # decoding again.
  83. # We use stderr's encoding because it's less likely to be
  84. # redirected and if we don't find an encoding we skip this
  85. # step (on the assumption that output is wrapped by something
  86. # that won't fail).
  87. # The double getattr is to deal with the possibility that we're
  88. # being called in a situation where sys.__stderr__ doesn't exist,
  89. # or doesn't have an encoding attribute. Neither of these cases
  90. # should occur in normal pip use, but there's no harm in checking
  91. # in case people use pip in (unsupported) unusual situations.
  92. output_encoding = getattr(getattr(sys, "__stderr__", None),
  93. "encoding", None)
  94. if output_encoding:
  95. s = s.encode(output_encoding, errors="backslashreplace")
  96. s = s.decode(output_encoding)
  97. return s
  98. if sys.version_info >= (3,):
  99. def native_str(s, replace=False):
  100. if isinstance(s, bytes):
  101. return s.decode('utf-8', 'replace' if replace else 'strict')
  102. return s
  103. else:
  104. def native_str(s, replace=False):
  105. # Replace is ignored -- unicode to UTF-8 can't fail
  106. if isinstance(s, text_type):
  107. return s.encode('utf-8')
  108. return s
  109. def get_path_uid(path):
  110. """
  111. Return path's uid.
  112. Does not follow symlinks:
  113. https://github.com/pypa/pip/pull/935#discussion_r5307003
  114. Placed this function in compat due to differences on AIX and
  115. Jython, that should eventually go away.
  116. :raises OSError: When path is a symlink or can't be read.
  117. """
  118. if hasattr(os, 'O_NOFOLLOW'):
  119. fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
  120. file_uid = os.fstat(fd).st_uid
  121. os.close(fd)
  122. else: # AIX and Jython
  123. # WARNING: time of check vulnerability, but best we can do w/o NOFOLLOW
  124. if not os.path.islink(path):
  125. # older versions of Jython don't have `os.fstat`
  126. file_uid = os.stat(path).st_uid
  127. else:
  128. # raise OSError for parity with os.O_NOFOLLOW above
  129. raise OSError(
  130. "%s is a symlink; Will not return uid for symlinks" % path
  131. )
  132. return file_uid
  133. if sys.version_info >= (3, 4):
  134. from importlib.machinery import EXTENSION_SUFFIXES
  135. def get_extension_suffixes():
  136. return EXTENSION_SUFFIXES
  137. else:
  138. from imp import get_suffixes
  139. def get_extension_suffixes():
  140. return [suffix[0] for suffix in get_suffixes()]
  141. def expanduser(path):
  142. """
  143. Expand ~ and ~user constructions.
  144. Includes a workaround for https://bugs.python.org/issue14768
  145. """
  146. expanded = os.path.expanduser(path)
  147. if path.startswith('~/') and expanded.startswith('//'):
  148. expanded = expanded[1:]
  149. return expanded
  150. # packages in the stdlib that may have installation metadata, but should not be
  151. # considered 'installed'. this theoretically could be determined based on
  152. # dist.location (py27:`sysconfig.get_paths()['stdlib']`,
  153. # py26:sysconfig.get_config_vars('LIBDEST')), but fear platform variation may
  154. # make this ineffective, so hard-coding
  155. stdlib_pkgs = {"python", "wsgiref", "argparse"}
  156. # windows detection, covers cpython and ironpython
  157. WINDOWS = (sys.platform.startswith("win") or
  158. (sys.platform == 'cli' and os.name == 'nt'))
  159. def samefile(file1, file2):
  160. """Provide an alternative for os.path.samefile on Windows/Python2"""
  161. if hasattr(os.path, 'samefile'):
  162. return os.path.samefile(file1, file2)
  163. else:
  164. path1 = os.path.normcase(os.path.abspath(file1))
  165. path2 = os.path.normcase(os.path.abspath(file2))
  166. return path1 == path2
  167. if hasattr(shutil, 'get_terminal_size'):
  168. def get_terminal_size():
  169. """
  170. Returns a tuple (x, y) representing the width(x) and the height(y)
  171. in characters of the terminal window.
  172. """
  173. return tuple(shutil.get_terminal_size())
  174. else:
  175. def get_terminal_size():
  176. """
  177. Returns a tuple (x, y) representing the width(x) and the height(y)
  178. in characters of the terminal window.
  179. """
  180. def ioctl_GWINSZ(fd):
  181. try:
  182. import fcntl
  183. import termios
  184. import struct
  185. cr = struct.unpack_from(
  186. 'hh',
  187. fcntl.ioctl(fd, termios.TIOCGWINSZ, '12345678')
  188. )
  189. except Exception:
  190. return None
  191. if cr == (0, 0):
  192. return None
  193. return cr
  194. cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
  195. if not cr:
  196. try:
  197. fd = os.open(os.ctermid(), os.O_RDONLY)
  198. cr = ioctl_GWINSZ(fd)
  199. os.close(fd)
  200. except Exception:
  201. pass
  202. if not cr:
  203. cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80))
  204. return int(cr[1]), int(cr[0])