compat.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. if desc is None:
  98. desc = 'Bytes object'
  99. msg_format = '{} does not appear to be encoded as %s'.format(desc)
  100. logger.warning(msg_format, encoding)
  101. decoded_data = data.decode(encoding, errors=backslashreplace_decode)
  102. # Make sure we can print the output, by encoding it to the output
  103. # encoding with replacement of unencodable characters, and then
  104. # decoding again.
  105. # We use stderr's encoding because it's less likely to be
  106. # redirected and if we don't find an encoding we skip this
  107. # step (on the assumption that output is wrapped by something
  108. # that won't fail).
  109. # The double getattr is to deal with the possibility that we're
  110. # being called in a situation where sys.__stderr__ doesn't exist,
  111. # or doesn't have an encoding attribute. Neither of these cases
  112. # should occur in normal pip use, but there's no harm in checking
  113. # in case people use pip in (unsupported) unusual situations.
  114. output_encoding = getattr(getattr(sys, "__stderr__", None),
  115. "encoding", None)
  116. if output_encoding:
  117. output_encoded = decoded_data.encode(
  118. output_encoding,
  119. errors="backslashreplace"
  120. )
  121. decoded_data = output_encoded.decode(output_encoding)
  122. return decoded_data
  123. def console_to_str(data):
  124. # type: (bytes) -> Text
  125. """Return a string, safe for output, of subprocess output.
  126. """
  127. return str_to_display(data, desc='Subprocess output')
  128. def get_path_uid(path):
  129. # type: (str) -> int
  130. """
  131. Return path's uid.
  132. Does not follow symlinks:
  133. https://github.com/pypa/pip/pull/935#discussion_r5307003
  134. Placed this function in compat due to differences on AIX and
  135. Jython, that should eventually go away.
  136. :raises OSError: When path is a symlink or can't be read.
  137. """
  138. if hasattr(os, 'O_NOFOLLOW'):
  139. fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
  140. file_uid = os.fstat(fd).st_uid
  141. os.close(fd)
  142. else: # AIX and Jython
  143. # WARNING: time of check vulnerability, but best we can do w/o NOFOLLOW
  144. if not os.path.islink(path):
  145. # older versions of Jython don't have `os.fstat`
  146. file_uid = os.stat(path).st_uid
  147. else:
  148. # raise OSError for parity with os.O_NOFOLLOW above
  149. raise OSError(
  150. "{} is a symlink; Will not return uid for symlinks".format(
  151. path)
  152. )
  153. return file_uid
  154. def expanduser(path):
  155. # type: (str) -> str
  156. """
  157. Expand ~ and ~user constructions.
  158. Includes a workaround for https://bugs.python.org/issue14768
  159. """
  160. expanded = os.path.expanduser(path)
  161. if path.startswith('~/') and expanded.startswith('//'):
  162. expanded = expanded[1:]
  163. return expanded
  164. # packages in the stdlib that may have installation metadata, but should not be
  165. # considered 'installed'. this theoretically could be determined based on
  166. # dist.location (py27:`sysconfig.get_paths()['stdlib']`,
  167. # py26:sysconfig.get_config_vars('LIBDEST')), but fear platform variation may
  168. # make this ineffective, so hard-coding
  169. stdlib_pkgs = {"python", "wsgiref", "argparse"}
  170. # windows detection, covers cpython and ironpython
  171. WINDOWS = (sys.platform.startswith("win") or
  172. (sys.platform == 'cli' and os.name == 'nt'))
  173. def samefile(file1, file2):
  174. # type: (str, str) -> bool
  175. """Provide an alternative for os.path.samefile on Windows/Python2"""
  176. if hasattr(os.path, 'samefile'):
  177. return os.path.samefile(file1, file2)
  178. else:
  179. path1 = os.path.normcase(os.path.abspath(file1))
  180. path2 = os.path.normcase(os.path.abspath(file2))
  181. return path1 == path2
  182. if hasattr(shutil, 'get_terminal_size'):
  183. def get_terminal_size():
  184. # type: () -> Tuple[int, int]
  185. """
  186. Returns a tuple (x, y) representing the width(x) and the height(y)
  187. in characters of the terminal window.
  188. """
  189. return tuple(shutil.get_terminal_size()) # type: ignore
  190. else:
  191. def get_terminal_size():
  192. # type: () -> Tuple[int, int]
  193. """
  194. Returns a tuple (x, y) representing the width(x) and the height(y)
  195. in characters of the terminal window.
  196. """
  197. def ioctl_GWINSZ(fd):
  198. try:
  199. import fcntl
  200. import termios
  201. import struct
  202. cr = struct.unpack_from(
  203. 'hh',
  204. fcntl.ioctl(fd, termios.TIOCGWINSZ, '12345678')
  205. )
  206. except Exception:
  207. return None
  208. if cr == (0, 0):
  209. return None
  210. return cr
  211. cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
  212. if not cr:
  213. if sys.platform != "win32":
  214. try:
  215. fd = os.open(os.ctermid(), os.O_RDONLY)
  216. cr = ioctl_GWINSZ(fd)
  217. os.close(fd)
  218. except Exception:
  219. pass
  220. if not cr:
  221. cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80))
  222. return int(cr[1]), int(cr[0])