Coverage for sources/mimeogram/parts.py: 100%
43 statements
« prev ^ index » next coverage.py v7.9.2, created at 2025-07-05 19:15 +0000
« prev ^ index » next coverage.py v7.9.2, created at 2025-07-05 19:15 +0000
1# vim: set filetype=python fileencoding=utf-8:
2# -*- coding: utf-8 -*-
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#============================================================================#
21''' Mimeogram parts. '''
24from . import __
25from . import fsprotect as _fsprotect
28class LineSeparators( __.enum.Enum ):
29 ''' Line separators for various platforms. '''
31 CR = '\r' # Classic MacOS
32 CRLF = '\r\n' # DOS/Windows
33 LF = '\n' # Unix/Linux
35 @classmethod
36 def detect_bytes(
37 selfclass, content: bytes, limit = 1024
38 ) -> "LineSeparators | None":
39 ''' Detects newline characters in bytes array. '''
40 sample = content[ : limit ]
41 found_cr = False
42 for byte in sample:
43 match byte:
44 case 0xd:
45 if found_cr: return selfclass.CR
46 found_cr = True
47 case 0xa: # linefeed
48 if found_cr: return selfclass.CRLF
49 return selfclass.LF
50 case _:
51 if found_cr: return selfclass.CR
52 return None
54 @classmethod
55 def normalize_universal( selfclass, content: str ) -> str:
56 ''' Normalizes all varieties of newline characters in text. '''
57 return content.replace( '\r\n', '\r' ).replace( '\r', '\n' )
59 def nativize( self, content: str ) -> str:
60 ''' Nativizes specific variety newline characters in text. '''
61 if LineSeparators.LF is self: return content
62 return content.replace( '\n', self.value )
64 def normalize( self, content: str ) -> str:
65 ''' Normalizes specific variety newline characters in text. '''
66 if LineSeparators.LF is self: return content
67 return content.replace( self.value, '\n' )
70class Resolutions( __.enum.Enum ):
71 ''' Available resolutions for each part. '''
73 Apply = 'apply'
74 Ignore = 'ignore'
77class Part( __.immut.DataclassObject ):
78 ''' Part of mimeogram. '''
79 location: str # TODO? 'Url' class
80 mimetype: str
81 charset: str
82 linesep: "LineSeparators"
83 content: str
85 # TODO? 'format' method
86 # TODO? 'parse' method
89class Target( __.immut.DataclassObject ):
90 ''' Target information for mimeogram part. '''
91 part: Part
92 destination: __.Path
93 protection: _fsprotect.Status