Coverage for sources/mimeogram/formatters.py: 100%

18 statements  

« prev     ^ index     » next       coverage.py v7.6.12, created at 2025-02-16 02:11 +0000

1# vim: set filetype=python fileencoding=utf-8: 

2# -*- coding: utf-8 -*- 

3 

4#============================================================================# 

5# # 

6# Licensed under the Apache License, Version 2.0 (the "License"); # 

7# you may not use this file except in compliance with the License. # 

8# You may obtain a copy of the License at # 

9# # 

10# http://www.apache.org/licenses/LICENSE-2.0 # 

11# # 

12# Unless required by applicable law or agreed to in writing, software # 

13# distributed under the License is distributed on an "AS IS" BASIS, # 

14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # 

15# See the License for the specific language governing permissions and # 

16# limitations under the License. # 

17# # 

18#============================================================================# 

19 

20 

21''' Formatting of mimeogram bundles. ''' 

22 

23 

24from __future__ import annotations 

25 

26from . import __ 

27from . import parts as _parts 

28 

29 

30def format_mimeogram( 

31 parts: __.cabc.Sequence[ _parts.Part ], 

32 message: __.typx.Optional[ str ] = None, 

33) -> str: 

34 ''' Formats parts into mimeogram. ''' 

35 if not parts and message is None: 

36 from .exceptions import MimeogramFormatEmpty 

37 raise MimeogramFormatEmpty( ) 

38 boundary = "====MIMEOGRAM_{uuid}====".format( uuid = __.uuid4( ).hex ) 

39 lines: list[ str ] = [ ] 

40 if message: 

41 message_part = _parts.Part( 

42 location = 'mimeogram://message', 

43 mimetype = 'text/plain', # TODO? Markdown 

44 charset = 'utf-8', 

45 linesep = _parts.LineSeparators.LF, 

46 content = message ) 

47 lines.append( format_part( message_part, boundary ) ) 

48 for part in parts: 

49 lines.append( format_part( part, boundary ) ) 

50 lines.append( f"--{boundary}--" ) 

51 return '\n'.join( lines ) 

52 

53 

54def format_part( part: _parts.Part, boundary: str ) -> str: 

55 ''' Formats part with boundary marker and headers. ''' 

56 return '\n'.join( ( 

57 f"--{boundary}", 

58 f"Content-Location: {part.location}", 

59 f"Content-Type: {part.mimetype}; " 

60 f"charset={part.charset}; " 

61 f"linesep={part.linesep.name}", 

62 '', 

63 part.content ) )