Reapply "gh-132947: Apply changes from importlib_metadata 8.7 (#137885)" (#137924) (#137930)

* Reapply "gh-132947: Apply changes from importlib_metadata 8.7 (#137885)" (#137924)

This reverts commit 3706ef66ef.

* Skip the triggering test on buildbots only.
This commit is contained in:
Jason R. Coombs 2025-09-01 11:27:01 -04:00 committed by GitHub
parent 2a54acf3c3
commit 9b38c6698a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 311 additions and 122 deletions

View file

@ -1,11 +1,58 @@
import email.message
import email.policy
import re
import textwrap
import email.message
from ._text import FoldedCase
class RawPolicy(email.policy.EmailPolicy):
def fold(self, name, value):
folded = self.linesep.join(
textwrap.indent(value, prefix=' ' * 8, predicate=lambda line: True)
.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.
... <BLANKLINE>
... Fourth line!
... ''').lstrip().replace('<BLANKLINE>', '')
>>> msg = Message(email.message_from_string(msg_text))
>>> msg['Description']
'First line of description.\nSecond line of description.\n\nFourth line!\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>
Fourth line!
<BLANKLINE>
<BLANKLINE>
"""
multiple_use_keys = set(
map(
FoldedCase,
@ -57,15 +104,20 @@ def __getitem__(self, item):
def _repair_headers(self):
def redent(value):
"Correct for RFC822 indentation"
if not value or '\n' not in value:
indent = ' ' * 8
if not value or '\n' + indent not in value:
return value
return textwrap.dedent(' ' * 8 + value)
return textwrap.dedent(indent + value)
headers = [(key, redent(value)) for key, value in vars(self)['_headers']]
if self._payload:
headers.append(('Description', self.get_payload()))
self.set_payload('')
return headers
def as_string(self):
return super().as_string(policy=RawPolicy())
@property
def json(self):
"""