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.

encoding.py 1.2KB

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