diff options
-rw-r--r-- | distixlib/__init__.py | 1 | ||||
-rw-r--r-- | distixlib/message_renderer.py | 62 | ||||
-rw-r--r-- | without-tests | 1 |
3 files changed, 64 insertions, 0 deletions
diff --git a/distixlib/__init__.py b/distixlib/__init__.py index d22ba60..85d69f1 100644 --- a/distixlib/__init__.py +++ b/distixlib/__init__.py @@ -37,6 +37,7 @@ from .ticket_store import ( TicketAlreadyInStoreError, TicketNotInStoreError) from .message_thread import MessageThread +from .message_renderer import MessageRenderer from .repo import Repository from .git import Git from .util import get_ticket_ids diff --git a/distixlib/message_renderer.py b/distixlib/message_renderer.py new file mode 100644 index 0000000..c9fe7b3 --- /dev/null +++ b/distixlib/message_renderer.py @@ -0,0 +1,62 @@ +# Copyright 2016 Lars Wirzenius +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# +# =*= License: GPL-3+ =*= + + +import email + + +class MessageRenderer(object): + + def summary(self, msg, output): + sender = self._get_header(msg, 'From') + body = self._plain_text_body(msg) + indented_body = self._indent(body.strip()) + output.write('From: {}\n\n{}\n'.format(sender, indented_body)) + + def _indent(self, text): + fmt = ' {}\n' + return ''.join(fmt.format(line) for line in text.splitlines()) + + def _get_header(self, msg, name): + decoded = email.header.decode_header(msg[name]) + combined = u' '.join( + value.decode(encoding or 'us-ascii') + for value, encoding in decoded) + return combined.encode('utf8') + + def _plain_text_body(self, msg): + body = self._find_first_plain_text_part(msg) + if body is None: + return '' + text = self._get_payload_as_unicode(body) + return self._strip_signature(text).encode('utf8') + + def _find_first_plain_text_part(self, msg): + for part in msg.walk(): + if part.get_content_type() == 'text/plain': + return part + return None + + def _get_payload_as_unicode(self, body): + charset = body.get_param('charset', 'us-ascii') + text = body.get_payload(decode=True) + return text.decode(charset) + + def _strip_signature(self, text): + sigsep = '\n-- \n' + parts = text.split(sigsep) + return parts[0] diff --git a/without-tests b/without-tests index f2d9ac9..12f58cb 100644 --- a/without-tests +++ b/without-tests @@ -14,3 +14,4 @@ distixlib/constants.py distixlib/git.py distixlib/version.py distixlib/util.py +distixlib/message_renderer.py |