encoding.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # The following comment should be removed at some point in the future.
  2. # mypy: strict-optional=False
  3. import codecs
  4. import locale
  5. import re
  6. import sys
  7. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  8. if MYPY_CHECK_RUNNING:
  9. from typing import List, Tuple, Text
  10. BOMS = [
  11. (codecs.BOM_UTF8, 'utf-8'),
  12. (codecs.BOM_UTF16, 'utf-16'),
  13. (codecs.BOM_UTF16_BE, 'utf-16-be'),
  14. (codecs.BOM_UTF16_LE, 'utf-16-le'),
  15. (codecs.BOM_UTF32, 'utf-32'),
  16. (codecs.BOM_UTF32_BE, 'utf-32-be'),
  17. (codecs.BOM_UTF32_LE, 'utf-32-le'),
  18. ] # type: List[Tuple[bytes, Text]]
  19. ENCODING_RE = re.compile(br'coding[:=]\s*([-\w.]+)')
  20. def auto_decode(data):
  21. # type: (bytes) -> Text
  22. """Check a bytes string for a BOM to correctly detect the encoding
  23. Fallback to locale.getpreferredencoding(False) like open() on Python3"""
  24. for bom, encoding in BOMS:
  25. if data.startswith(bom):
  26. return data[len(bom):].decode(encoding)
  27. # Lets check the first two lines as in PEP263
  28. for line in data.split(b'\n')[:2]:
  29. if line[0:1] == b'#' and ENCODING_RE.search(line):
  30. encoding = ENCODING_RE.search(line).groups()[0].decode('ascii')
  31. return data.decode(encoding)
  32. return data.decode(
  33. locale.getpreferredencoding(False) or sys.getdefaultencoding(),
  34. )