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