Coverage for sources/mimeogram/acquirers.py: 92%
131 statements
« prev ^ index » next coverage.py v7.6.12, created at 2025-02-17 22:34 +0000
« prev ^ index » next coverage.py v7.6.12, created at 2025-02-17 22:34 +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''' Content acquisition from various sources. '''
24from __future__ import annotations
26import aiofiles as _aiofiles
27import httpx as _httpx
29from . import __
30from . import exceptions as _exceptions
31from . import parts as _parts
34_scribe = __.produce_scribe( __name__ )
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 url_parts = (
48 urlparse( source ) if isinstance( source, str )
49 else urlparse( str( source ) ) )
50 match url_parts.scheme:
51 case '' | 'file':
52 tasks.extend( _produce_fs_tasks( source, recursive ) )
53 case 'http' | 'https':
54 tasks.append( _produce_http_task( str( source ) ) )
55 case _:
56 raise _exceptions.UrlSchemeNoSupport( str( source ) )
57 if strict: return await __.gather_async( *tasks )
58 results = await __.gather_async( *tasks, return_exceptions = True )
59 # TODO: Factor into '__.generics.extract_results_filter_errors'.
60 values: list[ _parts.Part ] = [ ]
61 for result in results:
62 if result.is_error( ):
63 _scribe.warning( str( result.error ) )
64 continue
65 values.append( result.extract( ) )
66 return tuple( values )
69async def _acquire_from_file( location: __.Path ) -> _parts.Part:
70 ''' Acquires content from text file. '''
71 from .exceptions import ContentAcquireFailure, ContentDecodeFailure
72 try:
73 async with _aiofiles.open( location, 'rb' ) as f:
74 content_bytes = await f.read( )
75 except Exception as exc: raise ContentAcquireFailure( location ) from exc
76 mimetype, charset = _detect_mimetype_and_charset( content_bytes, location )
77 if charset is None: raise ContentDecodeFailure( location, '???' ) 77 ↛ exitline 77 didn't except from function '_acquire_from_file' because the raise on line 77 wasn't executed
78 linesep = _parts.LineSeparators.detect_bytes( content_bytes )
79 # TODO? Separate error for newline issues.
80 if linesep is None: raise ContentDecodeFailure( location, charset ) 80 ↛ exitline 80 didn't except from function '_acquire_from_file' because the raise on line 80 wasn't executed
81 try: content = content_bytes.decode( charset )
82 except Exception as exc:
83 raise ContentDecodeFailure( location, charset ) from exc
84 _scribe.debug( f"Read file: {location}" )
85 return _parts.Part(
86 location = str( location ),
87 mimetype = mimetype,
88 charset = charset,
89 linesep = linesep,
90 content = linesep.normalize( content ) )
93async def _acquire_via_http( # pylint: disable=too-many-locals
94 client: _httpx.AsyncClient, url: str
95) -> _parts.Part:
96 ''' Acquires content via HTTP/HTTPS. '''
97 from .exceptions import ContentAcquireFailure, ContentDecodeFailure
98 try:
99 response = await client.get( url )
100 response.raise_for_status( )
101 except Exception as exc: raise ContentAcquireFailure( url ) from exc
102 mimetype = (
103 response.headers.get( 'content-type', 'application/octet-stream' )
104 .split( ';' )[ 0 ].strip( ) )
105 content_bytes = response.content
106 charset = response.encoding or _detect_charset( content_bytes )
107 if charset is None: raise ContentDecodeFailure( url, '???' ) 107 ↛ exitline 107 didn't except from function '_acquire_via_http' because the raise on line 107 wasn't executed
108 if not _is_textual_mimetype( mimetype ):
109 mimetype, _ = (
110 _detect_mimetype_and_charset(
111 content_bytes, url, charset = charset ) )
112 linesep = _parts.LineSeparators.detect_bytes( content_bytes )
113 # TODO? Separate error for newline issues.
114 if linesep is None: raise ContentDecodeFailure( url, charset ) 114 ↛ exitline 114 didn't except from function '_acquire_via_http' because the raise on line 114 wasn't executed
115 try: content = content_bytes.decode( charset )
116 except Exception as exc:
117 raise ContentDecodeFailure( url, charset ) from exc
118 _scribe.debug( f"Fetched URL: {url}" )
119 return _parts.Part(
120 location = url,
121 mimetype = mimetype,
122 charset = charset,
123 linesep = linesep,
124 content = linesep.normalize( content ) )
127# VCS directories to skip during traversal
128_VCS_DIRS = frozenset( ( '.git', '.svn', '.hg', '.bzr' ) )
129def _collect_directory_files(
130 directory: __.Path, recursive: bool
131) -> list[ __.Path ]:
132 ''' Collects and filters files from directory hierarchy. '''
133 import gitignorefile
134 cache = gitignorefile.Cache( )
135 paths: list[ __.Path ] = [ ]
136 _scribe.debug( f"Collecting files in directory: {directory}" )
137 for entry in directory.iterdir( ):
138 if entry.is_dir( ) and entry.name in _VCS_DIRS:
139 _scribe.debug( f"Ignoring VCS directory: {entry}" )
140 continue
141 if cache( str( entry ) ):
142 _scribe.debug( f"Ignoring path (matched by .gitignore): {entry}" )
143 continue
144 if entry.is_dir( ) and recursive:
145 paths.extend( _collect_directory_files( entry, recursive ) )
146 elif entry.is_file( ): paths.append( entry )
147 return paths
150def _detect_charset( content: bytes ) -> str | None:
151 # TODO: Pyright bug: `None is charset` != `charset is None`
152 from chardet import detect
153 charset = detect( content )[ 'encoding' ]
154 if charset is None: return charset 154 ↛ exitline 154 didn't return from function '_detect_charset' because the return on line 154 wasn't executed
155 if charset.startswith( 'utf' ): return charset
156 match charset:
157 case 'ascii': return 'utf-8' # Assume superset.
158 case _: pass
159 # Shake out false positives, like 'MacRoman'.
160 try: content.decode( 'utf-8' )
161 except UnicodeDecodeError: return charset
162 return 'utf-8'
165def _detect_mimetype( content: bytes, location: str | __.Path ) -> str | None:
166 from mimetypes import guess_type
167 from puremagic import PureError, from_string # pyright: ignore
168 try: return from_string( content, mime = True )
169 except ( PureError, ValueError ):
170 return guess_type( str( location ) )[ 0 ]
173def _detect_mimetype_and_charset(
174 content: bytes,
175 location: str | __.Path, *,
176 mimetype: __.Absential[ str ] = __.absent,
177 charset: __.Absential[ str ] = __.absent,
178) -> tuple[ str, str | None ]:
179 from .exceptions import TextualMimetypeInvalidity
180 if __.is_absent( mimetype ): 180 ↛ 182line 180 didn't jump to line 182 because the condition on line 180 was always true
181 mimetype_ = _detect_mimetype( content, location )
182 else: mimetype_ = mimetype
183 if __.is_absent( charset ):
184 charset_ = _detect_charset( content )
185 else: charset_ = charset
186 if not mimetype_:
187 if charset_: mimetype_ = 'text/plain' # pylint: disable=redefined-variable-type 187 ↛ 188line 187 didn't jump to line 188 because the condition on line 187 was always true
188 else: mimetype_ = 'application/octet-stream'
189 if not _is_textual_mimetype( mimetype_ ):
190 raise TextualMimetypeInvalidity( location, mimetype_ )
191 return mimetype_, charset_
194# MIME types that are considered textual beyond those starting with 'text/'
195_TEXTUAL_MIME_TYPES = frozenset( (
196 'application/json',
197 'application/xml',
198 'application/xhtml+xml',
199 'application/javascript',
200 'image/svg+xml',
201) )
202def _is_textual_mimetype( mimetype: str ) -> bool:
203 ''' Checks if MIME type represents textual content. '''
204 _scribe.debug( f"MIME type: {mimetype}" )
205 if mimetype.startswith( ( 'text/', 'application/x-', 'text/x-' ) ):
206 return True
207 return mimetype in _TEXTUAL_MIME_TYPES
210def _produce_fs_tasks(
211 location: str | __.Path, recursive: bool = False
212) -> tuple[ __.cabc.Coroutine[ None, None, _parts.Part ], ...]:
213 location_ = __.Path( location )
214 if location_.is_file( ) or location_.is_symlink( ):
215 return ( _acquire_from_file( location_ ), )
216 if location_.is_dir( ):
217 files = _collect_directory_files( location_, recursive )
218 return tuple( _acquire_from_file( f ) for f in files )
219 raise _exceptions.ContentAcquireFailure( location )
222def _produce_http_task(
223 url: str
224) -> __.cabc.Coroutine[ None, None, _parts.Part ]:
225 # TODO: URL object rather than string.
226 # TODO: Reuse clients for common hosts.
228 async def _execute_session( ) -> _parts.Part:
229 async with _httpx.AsyncClient( # nosec B113
230 follow_redirects = True
231 ) as client: return await _acquire_via_http( client, url )
233 return _execute_session( )