Skip to content

Commit

Permalink
Add support for rendering metadata where some fields have newlines (p…
Browse files Browse the repository at this point in the history
  • Loading branch information
jaraco committed Jan 20, 2025
1 parent b92ec18 commit 07aa607
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
46 changes: 46 additions & 0 deletions importlib_metadata/_adapters.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,54 @@
import email.message
import email.policy
import re
import textwrap

from ._text import FoldedCase


class RawPolicy(email.policy.EmailPolicy):
def fold(self, name, value):
folded = self.linesep.join(
textwrap.indent(value, prefix=' ' * 8).lstrip().splitlines()
)
return f'{name}: {folded}{self.linesep}'


class Message(email.message.Message):
r"""
Specialized Message subclass to handle metadata naturally.
Reads values that may have newlines in them and converts the
payload to the Description.
>>> msg_text = textwrap.dedent('''
... Name: Foo
... Version: 3.0
... License: blah
... de-blah
... <BLANKLINE>
... First line of description.
... Second line of description.
... ''').lstrip().replace('<BLANKLINE>', '')
>>> msg = Message(email.message_from_string(msg_text))
>>> msg['Description']
'First line of description.\nSecond line of description.\n'
Message should render even if values contain newlines.
>>> print(msg)
Name: Foo
Version: 3.0
License: blah
de-blah
Description: First line of description.
Second line of description.
<BLANKLINE>
First line of description.
Second line of description.
<BLANKLINE>
"""

multiple_use_keys = set(
map(
FoldedCase,
Expand Down Expand Up @@ -67,6 +110,9 @@ def redent(value):
headers.append(('Description', self.get_payload()))
return headers

def as_string(self):
return super().as_string(policy=RawPolicy())

@property
def json(self):
"""
Expand Down
1 change: 1 addition & 0 deletions newsfragments/+f9f493e6.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add support for rendering metadata where some fields have newlines (python/cpython#119650).

0 comments on commit 07aa607

Please sign in to comment.