Skip to content

Commit 29097d5

Browse files
committed
Merge: python#19003: Only replace \r and/or \n line endings in email.generator.
1 parent 727cc93 commit 29097d5

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

Lib/email/generator.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
UNDERSCORE = '_'
1919
NL = '\n' # XXX: no longer used by the code below.
2020

21+
NLCRE = re.compile(r'\r\n|\r|\n')
2122
fcre = re.compile(r'^From ', re.MULTILINE)
2223

2324

@@ -149,14 +150,17 @@ def _write_lines(self, lines):
149150
# We have to transform the line endings.
150151
if not lines:
151152
return
152-
lines = lines.splitlines(True)
153+
lines = NLCRE.split(lines)
153154
for line in lines[:-1]:
154-
self.write(line.rstrip('\r\n'))
155-
self.write(self._NL)
156-
laststripped = lines[-1].rstrip('\r\n')
157-
self.write(laststripped)
158-
if len(lines[-1]) != len(laststripped):
155+
self.write(line)
159156
self.write(self._NL)
157+
if lines[-1]:
158+
self.write(lines[-1])
159+
# XXX logic tells me this else should be needed, but the tests fail
160+
# with it and pass without it. (NLCRE.split ends with a blank element
161+
# if and only if there was a trailing newline.)
162+
#else:
163+
# self.write(self._NL)
160164

161165
def _write(self, msg):
162166
# We can't write the headers yet because of the following scenario:

Lib/test/test_email/test_email.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1599,6 +1599,18 @@ def test_binary_body_with_encode_noop(self):
15991599
self.assertEqual(msg.get_payload(), '\uFFFD' * len(bytesdata))
16001600
self.assertEqual(msg2.get_payload(decode=True), bytesdata)
16011601

1602+
def test_binary_body_with_unicode_linend_encode_noop(self):
1603+
# Issue 19003: This is a variation on #16564.
1604+
bytesdata = b'\x0b\xfa\xfb\xfc\xfd\xfe\xff'
1605+
msg = MIMEApplication(bytesdata, _encoder=encoders.encode_noop)
1606+
self.assertEqual(msg.get_payload(decode=True), bytesdata)
1607+
s = BytesIO()
1608+
g = BytesGenerator(s)
1609+
g.flatten(msg)
1610+
wireform = s.getvalue()
1611+
msg2 = email.message_from_bytes(wireform)
1612+
self.assertEqual(msg2.get_payload(decode=True), bytesdata)
1613+
16021614
def test_binary_body_with_encode_quopri(self):
16031615
# Issue 14360.
16041616
bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff '

0 commit comments

Comments
 (0)