compat.py 8.7 KB

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