pkginfo.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. """Tools for reading and writing PKG-INFO / METADATA without caring
  2. about the encoding."""
  3. from email.parser import Parser
  4. try:
  5. unicode
  6. _PY3 = False
  7. except NameError:
  8. _PY3 = True
  9. if not _PY3:
  10. from email.generator import Generator
  11. def read_pkg_info_bytes(bytestr):
  12. return Parser().parsestr(bytestr)
  13. def read_pkg_info(path):
  14. with open(path, "r") as headers:
  15. message = Parser().parse(headers)
  16. return message
  17. def write_pkg_info(path, message):
  18. with open(path, 'w') as metadata:
  19. Generator(metadata, mangle_from_=False, maxheaderlen=0).flatten(message)
  20. else:
  21. from email.generator import BytesGenerator
  22. def read_pkg_info_bytes(bytestr):
  23. headers = bytestr.decode(encoding="ascii", errors="surrogateescape")
  24. message = Parser().parsestr(headers)
  25. return message
  26. def read_pkg_info(path):
  27. with open(path, "r",
  28. encoding="ascii",
  29. errors="surrogateescape") as headers:
  30. message = Parser().parse(headers)
  31. return message
  32. def write_pkg_info(path, message):
  33. with open(path, "wb") as out:
  34. BytesGenerator(out, mangle_from_=False, maxheaderlen=0).flatten(message)