Skip to content

Commit 07aa607

Browse files
committed
Add support for rendering metadata where some fields have newlines (python/cpython#119650).
1 parent b92ec18 commit 07aa607

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

importlib_metadata/_adapters.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,54 @@
11
import email.message
2+
import email.policy
23
import re
34
import textwrap
45

56
from ._text import FoldedCase
67

78

9+
class RawPolicy(email.policy.EmailPolicy):
10+
def fold(self, name, value):
11+
folded = self.linesep.join(
12+
textwrap.indent(value, prefix=' ' * 8).lstrip().splitlines()
13+
)
14+
return f'{name}: {folded}{self.linesep}'
15+
16+
817
class Message(email.message.Message):
18+
r"""
19+
Specialized Message subclass to handle metadata naturally.
20+
21+
Reads values that may have newlines in them and converts the
22+
payload to the Description.
23+
24+
>>> msg_text = textwrap.dedent('''
25+
... Name: Foo
26+
... Version: 3.0
27+
... License: blah
28+
... de-blah
29+
... <BLANKLINE>
30+
... First line of description.
31+
... Second line of description.
32+
... ''').lstrip().replace('<BLANKLINE>', '')
33+
>>> msg = Message(email.message_from_string(msg_text))
34+
>>> msg['Description']
35+
'First line of description.\nSecond line of description.\n'
36+
37+
Message should render even if values contain newlines.
38+
39+
>>> print(msg)
40+
Name: Foo
41+
Version: 3.0
42+
License: blah
43+
de-blah
44+
Description: First line of description.
45+
Second line of description.
46+
<BLANKLINE>
47+
First line of description.
48+
Second line of description.
49+
<BLANKLINE>
50+
"""
51+
952
multiple_use_keys = set(
1053
map(
1154
FoldedCase,
@@ -67,6 +110,9 @@ def redent(value):
67110
headers.append(('Description', self.get_payload()))
68111
return headers
69112

113+
def as_string(self):
114+
return super().as_string(policy=RawPolicy())
115+
70116
@property
71117
def json(self):
72118
"""

newsfragments/+f9f493e6.feature.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add support for rendering metadata where some fields have newlines (python/cpython#119650).

0 commit comments

Comments
 (0)