Coverage for sources/mimeogram/acquirers.py: 92%

133 statements  

« prev     ^ index     » next       coverage.py v7.6.12, created at 2025-03-02 23:41 +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''' Content acquisition from various sources. ''' 

22 

23 

24from __future__ import annotations 

25 

26import aiofiles as _aiofiles 

27import httpx as _httpx 

28 

29from . import __ 

30from . import exceptions as _exceptions 

31from . import parts as _parts 

32 

33 

34_scribe = __.produce_scribe( __name__ ) 

35 

36 

37async def acquire( # pylint: disable=too-many-locals 

38 auxdata: __.Globals, sources: __.cabc.Sequence[ str | __.Path ] 

39) -> __.cabc.Sequence[ _parts.Part ]: 

40 ''' Acquires content from multiple sources. ''' 

41 from urllib.parse import urlparse 

42 options = auxdata.configuration.get( 'acquire-parts', { } ) 

43 strict = options.get( 'fail-on-invalid', False ) 

44 recursive = options.get( 'recurse-directories', False ) 

45 tasks: list[ __.cabc.Coroutine[ None, None, _parts.Part ] ] = [ ] 

46 for source in sources: 

47 path = __.Path( source ) 

48 url_parts = ( 

49 urlparse( source ) if isinstance( source, str ) 

50 else urlparse( str( source ) ) ) 

51 scheme = 'file' if path.drive else url_parts.scheme 

52 match scheme: 

53 case '' | 'file': 

54 tasks.extend( _produce_fs_tasks( source, recursive ) ) 

55 case 'http' | 'https': 

56 tasks.append( _produce_http_task( str( source ) ) ) 

57 case _: 

58 raise _exceptions.UrlSchemeNoSupport( str( source ) ) 

59 if strict: return await __.gather_async( *tasks ) 

60 results = await __.gather_async( *tasks, return_exceptions = True ) 

61 # TODO: Factor into '__.generics.extract_results_filter_errors'. 

62 values: list[ _parts.Part ] = [ ] 

63 for result in results: 

64 if result.is_error( ): 

65 _scribe.warning( str( result.error ) ) 

66 continue 

67 values.append( result.extract( ) ) 

68 return tuple( values ) 

69 

70 

71async def _acquire_from_file( location: __.Path ) -> _parts.Part: 

72 ''' Acquires content from text file. ''' 

73 from .exceptions import ContentAcquireFailure, ContentDecodeFailure 

74 try: 

75 async with _aiofiles.open( location, 'rb' ) as f: 

76 content_bytes = await f.read( ) 

77 except Exception as exc: raise ContentAcquireFailure( location ) from exc 

78 mimetype, charset = _detect_mimetype_and_charset( content_bytes, location ) 

79 if charset is None: raise ContentDecodeFailure( location, '???' ) 79 ↛ exitline 79 didn't except from function '_acquire_from_file' because the raise on line 79 wasn't executed

80 linesep = _parts.LineSeparators.detect_bytes( content_bytes ) 

81 # TODO? Separate error for newline issues. 

82 if linesep is None: raise ContentDecodeFailure( location, charset ) 82 ↛ exitline 82 didn't except from function '_acquire_from_file' because the raise on line 82 wasn't executed

83 try: content = content_bytes.decode( charset ) 

84 except Exception as exc: 

85 raise ContentDecodeFailure( location, charset ) from exc 

86 _scribe.debug( f"Read file: {location}" ) 

87 return _parts.Part( 

88 location = str( location ), 

89 mimetype = mimetype, 

90 charset = charset, 

91 linesep = linesep, 

92 content = linesep.normalize( content ) ) 

93 

94 

95async def _acquire_via_http( # pylint: disable=too-many-locals 

96 client: _httpx.AsyncClient, url: str 

97) -> _parts.Part: 

98 ''' Acquires content via HTTP/HTTPS. ''' 

99 from .exceptions import ContentAcquireFailure, ContentDecodeFailure 

100 try: 

101 response = await client.get( url ) 

102 response.raise_for_status( ) 

103 except Exception as exc: raise ContentAcquireFailure( url ) from exc 

104 mimetype = ( 

105 response.headers.get( 'content-type', 'application/octet-stream' ) 

106 .split( ';' )[ 0 ].strip( ) ) 

107 content_bytes = response.content 

108 charset = response.encoding or _detect_charset( content_bytes ) 

109 if charset is None: raise ContentDecodeFailure( url, '???' ) 109 ↛ exitline 109 didn't except from function '_acquire_via_http' because the raise on line 109 wasn't executed

110 if not _is_textual_mimetype( mimetype ): 

111 mimetype, _ = ( 

112 _detect_mimetype_and_charset( 

113 content_bytes, url, charset = charset ) ) 

114 linesep = _parts.LineSeparators.detect_bytes( content_bytes ) 

115 # TODO? Separate error for newline issues. 

116 if linesep is None: raise ContentDecodeFailure( url, charset ) 116 ↛ exitline 116 didn't except from function '_acquire_via_http' because the raise on line 116 wasn't executed

117 try: content = content_bytes.decode( charset ) 

118 except Exception as exc: 

119 raise ContentDecodeFailure( url, charset ) from exc 

120 _scribe.debug( f"Fetched URL: {url}" ) 

121 return _parts.Part( 

122 location = url, 

123 mimetype = mimetype, 

124 charset = charset, 

125 linesep = linesep, 

126 content = linesep.normalize( content ) ) 

127 

128 

129# VCS directories to skip during traversal 

130_VCS_DIRS = frozenset( ( '.git', '.svn', '.hg', '.bzr' ) ) 

131def _collect_directory_files( 

132 directory: __.Path, recursive: bool 

133) -> list[ __.Path ]: 

134 ''' Collects and filters files from directory hierarchy. ''' 

135 import gitignorefile 

136 cache = gitignorefile.Cache( ) 

137 paths: list[ __.Path ] = [ ] 

138 _scribe.debug( f"Collecting files in directory: {directory}" ) 

139 for entry in directory.iterdir( ): 

140 if entry.is_dir( ) and entry.name in _VCS_DIRS: 

141 _scribe.debug( f"Ignoring VCS directory: {entry}" ) 

142 continue 

143 if cache( str( entry ) ): 

144 _scribe.debug( f"Ignoring path (matched by .gitignore): {entry}" ) 

145 continue 

146 if entry.is_dir( ) and recursive: 

147 paths.extend( _collect_directory_files( entry, recursive ) ) 

148 elif entry.is_file( ): paths.append( entry ) 

149 return paths 

150 

151 

152def _detect_charset( content: bytes ) -> str | None: 

153 # TODO: Pyright bug: `None is charset` != `charset is None` 

154 from chardet import detect 

155 charset = detect( content )[ 'encoding' ] 

156 if charset is None: return charset 156 ↛ exitline 156 didn't return from function '_detect_charset' because the return on line 156 wasn't executed

157 if charset.startswith( 'utf' ): return charset 

158 match charset: 

159 case 'ascii': return 'utf-8' # Assume superset. 

160 case _: pass 

161 # Shake out false positives, like 'MacRoman'. 

162 try: content.decode( 'utf-8' ) 

163 except UnicodeDecodeError: return charset 

164 return 'utf-8' 

165 

166 

167def _detect_mimetype( content: bytes, location: str | __.Path ) -> str | None: 

168 from mimetypes import guess_type 

169 from puremagic import PureError, from_string # pyright: ignore 

170 try: return from_string( content, mime = True ) 

171 except ( PureError, ValueError ): 

172 return guess_type( str( location ) )[ 0 ] 

173 

174 

175def _detect_mimetype_and_charset( 

176 content: bytes, 

177 location: str | __.Path, *, 

178 mimetype: __.Absential[ str ] = __.absent, 

179 charset: __.Absential[ str ] = __.absent, 

180) -> tuple[ str, str | None ]: 

181 from .exceptions import TextualMimetypeInvalidity 

182 if __.is_absent( mimetype ): 182 ↛ 184line 182 didn't jump to line 184 because the condition on line 182 was always true

183 mimetype_ = _detect_mimetype( content, location ) 

184 else: mimetype_ = mimetype 

185 if __.is_absent( charset ): 

186 charset_ = _detect_charset( content ) 

187 else: charset_ = charset 

188 if not mimetype_: 

189 if charset_: mimetype_ = 'text/plain' # pylint: disable=redefined-variable-type 189 ↛ 190line 189 didn't jump to line 190 because the condition on line 189 was always true

190 else: mimetype_ = 'application/octet-stream' 

191 if not _is_textual_mimetype( mimetype_ ): 

192 raise TextualMimetypeInvalidity( location, mimetype_ ) 

193 return mimetype_, charset_ 

194 

195 

196# MIME types that are considered textual beyond those starting with 'text/' 

197_TEXTUAL_MIME_TYPES = frozenset( ( 

198 'application/json', 

199 'application/xml', 

200 'application/xhtml+xml', 

201 'application/javascript', 

202 'image/svg+xml', 

203) ) 

204def _is_textual_mimetype( mimetype: str ) -> bool: 

205 ''' Checks if MIME type represents textual content. ''' 

206 _scribe.debug( f"MIME type: {mimetype}" ) 

207 if mimetype.startswith( ( 'text/', 'application/x-', 'text/x-' ) ): 

208 return True 

209 return mimetype in _TEXTUAL_MIME_TYPES 

210 

211 

212def _produce_fs_tasks( 

213 location: str | __.Path, recursive: bool = False 

214) -> tuple[ __.cabc.Coroutine[ None, None, _parts.Part ], ...]: 

215 location_ = __.Path( location ) 

216 if location_.is_file( ) or location_.is_symlink( ): 

217 return ( _acquire_from_file( location_ ), ) 

218 if location_.is_dir( ): 

219 files = _collect_directory_files( location_, recursive ) 

220 return tuple( _acquire_from_file( f ) for f in files ) 

221 raise _exceptions.ContentAcquireFailure( location ) 

222 

223 

224def _produce_http_task( 

225 url: str 

226) -> __.cabc.Coroutine[ None, None, _parts.Part ]: 

227 # TODO: URL object rather than string. 

228 # TODO: Reuse clients for common hosts. 

229 

230 async def _execute_session( ) -> _parts.Part: 

231 async with _httpx.AsyncClient( # nosec B113 

232 follow_redirects = True 

233 ) as client: return await _acquire_via_http( client, url ) 

234 

235 return _execute_session( )