SciFile-Core 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- scifile_core/__init__.py +111 -0
- scifile_core/_content.py +490 -0
- scifile_core/_diagnostic.py +322 -0
- scifile_core/_exception.py +221 -0
- scifile_core/_io.py +705 -0
- scifile_core/_mapping.py +139 -0
- scifile_core/_model.py +1056 -0
- scifile_core/_number.py +41 -0
- scifile_core/_optional.py +40 -0
- scifile_core/py.typed +0 -0
- scifile_core/testing.py +653 -0
- scifile_core/wording.py +454 -0
- scifile_core-0.0.1.dist-info/METADATA +6 -0
- scifile_core-0.0.1.dist-info/RECORD +16 -0
- scifile_core-0.0.1.dist-info/WHEEL +5 -0
- scifile_core-0.0.1.dist-info/top_level.txt +1 -0
scifile_core/_io.py
ADDED
|
@@ -0,0 +1,705 @@
|
|
|
1
|
+
"""Reading inputs, and writing to targets."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import codecs
|
|
6
|
+
import errno
|
|
7
|
+
import io
|
|
8
|
+
import os
|
|
9
|
+
import secrets
|
|
10
|
+
import stat
|
|
11
|
+
import zlib
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from functools import partial
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import TYPE_CHECKING, BinaryIO, overload
|
|
16
|
+
|
|
17
|
+
import fileex.file
|
|
18
|
+
|
|
19
|
+
from scifile_core import wording
|
|
20
|
+
from scifile_core._diagnostic import (
|
|
21
|
+
Diagnostic,
|
|
22
|
+
SharedDiagnosticType,
|
|
23
|
+
create_diagnostic,
|
|
24
|
+
)
|
|
25
|
+
from scifile_core._exception import InputError, describe
|
|
26
|
+
|
|
27
|
+
if TYPE_CHECKING:
|
|
28
|
+
from collections.abc import Callable, Iterable, Iterator
|
|
29
|
+
|
|
30
|
+
from fileex.typing import FileLike
|
|
31
|
+
|
|
32
|
+
from scifile_core._diagnostic import DiagnosticType
|
|
33
|
+
|
|
34
|
+
type TextTarget = Callable[[str], object] | str | os.PathLike[str] | None
|
|
35
|
+
"""Where text output goes: returned (`None`), to a callable, or to a path."""
|
|
36
|
+
|
|
37
|
+
type BinaryTarget = Callable[[bytes], object] | str | os.PathLike[str] | None
|
|
38
|
+
"""Where binary output goes: returned (`None`), to a callable, or to a path."""
|
|
39
|
+
|
|
40
|
+
_ASCII = bytes(range(128))
|
|
41
|
+
"""The bytes of ASCII, which an encoding must read and write as ASCII does."""
|
|
42
|
+
|
|
43
|
+
_MAX_PATH_CHARACTERS = 4096
|
|
44
|
+
"""Longest string that is checked for being the path of a file."""
|
|
45
|
+
|
|
46
|
+
_GZIP_MAGIC = b"\x1f\x8b\x08"
|
|
47
|
+
"""First bytes of gzip-compressed data: the two bytes of identification and
|
|
48
|
+
the compression method deflate, the only one that gzip defines."""
|
|
49
|
+
|
|
50
|
+
_GZIP_WBITS = 16 + zlib.MAX_WBITS
|
|
51
|
+
"""The value of `wbits` with which zlib reads one member of gzip."""
|
|
52
|
+
|
|
53
|
+
_PIECE_BYTES = 1 << 20
|
|
54
|
+
"""Bytes of compressed input read, and of output made, at a time."""
|
|
55
|
+
|
|
56
|
+
_TEMPORARY_ATTEMPTS = 100
|
|
57
|
+
"""Most names that writing a file tries for its new file."""
|
|
58
|
+
|
|
59
|
+
_NEW_FILE_MODE = 0o666
|
|
60
|
+
"""Mode of a new file, which the umask of the process narrows."""
|
|
61
|
+
|
|
62
|
+
_PRIVATE_MODE = 0o600
|
|
63
|
+
"""Mode of a file that only its owner can read and write."""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _replace_each(error: UnicodeError) -> tuple[str, int]:
|
|
67
|
+
"""Replace one undecodable byte by U+FFFD, and go on after it.
|
|
68
|
+
|
|
69
|
+
The handler `"replace"` replaces a truncated sequence of several bytes
|
|
70
|
+
by one U+FFFD, so that the text no longer tells how many bytes it spans.
|
|
71
|
+
|
|
72
|
+
Raises
|
|
73
|
+
------
|
|
74
|
+
UnicodeError
|
|
75
|
+
If the error is no error of decoding.
|
|
76
|
+
"""
|
|
77
|
+
if not isinstance(error, UnicodeDecodeError):
|
|
78
|
+
raise error
|
|
79
|
+
return ("\ufffd", error.start + 1)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
_REPLACE_EACH = "scifile_core.replace_each"
|
|
83
|
+
"""The name of the error handler that replaces each undecodable byte."""
|
|
84
|
+
|
|
85
|
+
codecs.register_error(_REPLACE_EACH, _replace_each)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(frozen=True, slots=True)
|
|
89
|
+
class TextSource:
|
|
90
|
+
"""The text of an input, and where it came from.
|
|
91
|
+
|
|
92
|
+
Attributes
|
|
93
|
+
----------
|
|
94
|
+
text
|
|
95
|
+
The text. Each byte that the encoding cannot decode is replaced by
|
|
96
|
+
one U+FFFD, also in a truncated sequence of several bytes, so that
|
|
97
|
+
a line of the text spans as many bytes of the input as its
|
|
98
|
+
characters take, with a U+FFFD of an undecodable byte as one.
|
|
99
|
+
path
|
|
100
|
+
The path that the text was read from, or `None`.
|
|
101
|
+
undecodable
|
|
102
|
+
Byte offset of the first byte that the encoding cannot decode,
|
|
103
|
+
or `None` if every byte was decoded.
|
|
104
|
+
"""
|
|
105
|
+
|
|
106
|
+
text: str
|
|
107
|
+
path: Path | None
|
|
108
|
+
undecodable: int | None
|
|
109
|
+
|
|
110
|
+
def diagnostics(
|
|
111
|
+
self, diagnostic_types: type[DiagnosticType]
|
|
112
|
+
) -> tuple[Diagnostic, ...]:
|
|
113
|
+
"""Return the diagnostics of decoding the text.
|
|
114
|
+
|
|
115
|
+
Parameters
|
|
116
|
+
----------
|
|
117
|
+
diagnostic_types
|
|
118
|
+
The package's ``DiagnosticType``, which repeats the shared type
|
|
119
|
+
`~scifile_core.SharedDiagnosticType.UNDECODABLE_TEXT`.
|
|
120
|
+
|
|
121
|
+
Returns
|
|
122
|
+
-------
|
|
123
|
+
A diagnostic of the type
|
|
124
|
+
`~scifile_core.SharedDiagnosticType.UNDECODABLE_TEXT` at the offset of
|
|
125
|
+
the first undecodable byte, if there is one, and nothing otherwise.
|
|
126
|
+
|
|
127
|
+
Raises
|
|
128
|
+
------
|
|
129
|
+
KeyError
|
|
130
|
+
If ``diagnostic_types`` has no member
|
|
131
|
+
`~scifile_core.SharedDiagnosticType.UNDECODABLE_TEXT`.
|
|
132
|
+
"""
|
|
133
|
+
if self.undecodable is None:
|
|
134
|
+
return ()
|
|
135
|
+
diagnostic_type = diagnostic_types[
|
|
136
|
+
SharedDiagnosticType.UNDECODABLE_TEXT.name
|
|
137
|
+
]
|
|
138
|
+
details = wording.undecodable_text(self.undecodable)
|
|
139
|
+
return (
|
|
140
|
+
create_diagnostic(
|
|
141
|
+
diagnostic_type, details, offset=self.undecodable
|
|
142
|
+
),
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@dataclass(frozen=True, slots=True)
|
|
147
|
+
class BinarySource:
|
|
148
|
+
"""The bytes of an input, and where they came from.
|
|
149
|
+
|
|
150
|
+
Attributes
|
|
151
|
+
----------
|
|
152
|
+
data
|
|
153
|
+
The bytes.
|
|
154
|
+
path
|
|
155
|
+
The path that the bytes were read from, or `None`.
|
|
156
|
+
"""
|
|
157
|
+
|
|
158
|
+
data: bytes
|
|
159
|
+
path: Path | None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def read_text(
|
|
163
|
+
file: FileLike,
|
|
164
|
+
*,
|
|
165
|
+
path_can_be_str: bool = True,
|
|
166
|
+
encoding: str = "utf-8",
|
|
167
|
+
input_error: type[InputError] | None = None,
|
|
168
|
+
) -> TextSource:
|
|
169
|
+
"""Read the text of an input of a text format.
|
|
170
|
+
|
|
171
|
+
Parameters
|
|
172
|
+
----------
|
|
173
|
+
file
|
|
174
|
+
A path, the text itself, bytes, or a readable stream, which is read
|
|
175
|
+
from its position to its end and then put back at that position.
|
|
176
|
+
Gzip-compressed content is decompressed.
|
|
177
|
+
path_can_be_str
|
|
178
|
+
Whether a string that names an existing file is read as its path.
|
|
179
|
+
Otherwise, every string is the text itself.
|
|
180
|
+
encoding
|
|
181
|
+
Encoding that decodes bytes; it must be ASCII-compatible.
|
|
182
|
+
A string and a text stream are text already.
|
|
183
|
+
input_error
|
|
184
|
+
The exception that a rejected argument raises, the package's own;
|
|
185
|
+
`None` for `InputError`.
|
|
186
|
+
|
|
187
|
+
Returns
|
|
188
|
+
-------
|
|
189
|
+
The text and where it came from. Undecodable bytes do not raise;
|
|
190
|
+
`TextSource.undecodable` gives the first of them. Bytes with an
|
|
191
|
+
undecodable byte are decoded twice, and reading them peaks at about
|
|
192
|
+
five times their size on Python 3.12, and six on Python 3.14, the bytes
|
|
193
|
+
included, since the U+FFFD makes every character of the text two bytes
|
|
194
|
+
wide.
|
|
195
|
+
|
|
196
|
+
Raises
|
|
197
|
+
------
|
|
198
|
+
InputError
|
|
199
|
+
If the encoding is unknown or not ASCII-compatible, a path names no
|
|
200
|
+
file, the input is of no supported type, or its gzip-compressed
|
|
201
|
+
content is corrupt or incomplete.
|
|
202
|
+
"""
|
|
203
|
+
input_error = input_error or InputError
|
|
204
|
+
check_encoding(encoding, input_error=input_error)
|
|
205
|
+
if isinstance(file, str) and not (path_can_be_str and _names_file(file)):
|
|
206
|
+
return TextSource(text=file, path=None, undecodable=None)
|
|
207
|
+
if isinstance(file, io.TextIOBase):
|
|
208
|
+
text = fileex.file.content(file, path_can_be_str=False, output="str")
|
|
209
|
+
return TextSource(text=text, path=None, undecodable=None)
|
|
210
|
+
source = _binary(file, encoding=encoding, input_error=input_error)
|
|
211
|
+
try:
|
|
212
|
+
text = source.data.decode(encoding)
|
|
213
|
+
except UnicodeDecodeError as error:
|
|
214
|
+
undecodable = error.start
|
|
215
|
+
else:
|
|
216
|
+
return TextSource(text=text, path=source.path, undecodable=None)
|
|
217
|
+
# Decoded again once the error, which holds a copy of the bytes, is freed.
|
|
218
|
+
text = source.data.decode(encoding, errors=_REPLACE_EACH)
|
|
219
|
+
return TextSource(text=text, path=source.path, undecodable=undecodable)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def read_bytes(
|
|
223
|
+
file: FileLike,
|
|
224
|
+
*,
|
|
225
|
+
input_error: type[InputError] | None = None,
|
|
226
|
+
) -> BinarySource:
|
|
227
|
+
"""Read the bytes of an input of a binary format.
|
|
228
|
+
|
|
229
|
+
Parameters
|
|
230
|
+
----------
|
|
231
|
+
file
|
|
232
|
+
A path (a string is always a path), bytes, or a binary stream, which
|
|
233
|
+
is read from its position to its end and then put back at that
|
|
234
|
+
position. Gzip-compressed content is decompressed.
|
|
235
|
+
input_error
|
|
236
|
+
The exception that a rejected argument raises, the package's own;
|
|
237
|
+
`None` for `InputError`.
|
|
238
|
+
|
|
239
|
+
Returns
|
|
240
|
+
-------
|
|
241
|
+
The bytes and where they came from. Bytes that are given as `bytes` are
|
|
242
|
+
returned without a copy.
|
|
243
|
+
|
|
244
|
+
Raises
|
|
245
|
+
------
|
|
246
|
+
InputError
|
|
247
|
+
If a path names no file, the input is a text stream or of no
|
|
248
|
+
supported type, or its gzip-compressed content is corrupt or
|
|
249
|
+
incomplete.
|
|
250
|
+
"""
|
|
251
|
+
input_error = input_error or InputError
|
|
252
|
+
if isinstance(file, io.TextIOBase):
|
|
253
|
+
raise input_error(
|
|
254
|
+
parameter="file",
|
|
255
|
+
argument=file,
|
|
256
|
+
message="is a text stream; use a binary one",
|
|
257
|
+
)
|
|
258
|
+
return _binary(file, encoding="utf-8", input_error=input_error)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def check_encoding(
|
|
262
|
+
encoding: str,
|
|
263
|
+
*,
|
|
264
|
+
input_error: type[InputError] | None = None,
|
|
265
|
+
) -> None:
|
|
266
|
+
"""Check that an encoding is known and ASCII-compatible.
|
|
267
|
+
|
|
268
|
+
Parameters
|
|
269
|
+
----------
|
|
270
|
+
encoding
|
|
271
|
+
Name of the encoding.
|
|
272
|
+
input_error
|
|
273
|
+
The exception that a rejected argument raises, the package's own;
|
|
274
|
+
`None` for `InputError`.
|
|
275
|
+
|
|
276
|
+
Raises
|
|
277
|
+
------
|
|
278
|
+
InputError
|
|
279
|
+
If the encoding is unknown, or does not read and write each of the
|
|
280
|
+
128 characters of ASCII as the byte that ASCII gives it, as UTF-16,
|
|
281
|
+
UTF-7 and the BOM of UTF-8-SIG do not.
|
|
282
|
+
"""
|
|
283
|
+
input_error = input_error or InputError
|
|
284
|
+
try:
|
|
285
|
+
codecs.lookup(encoding)
|
|
286
|
+
except LookupError:
|
|
287
|
+
raise input_error(
|
|
288
|
+
parameter="encoding",
|
|
289
|
+
argument=encoding,
|
|
290
|
+
message="is no known text encoding",
|
|
291
|
+
) from None
|
|
292
|
+
if not _ascii_compatible(encoding):
|
|
293
|
+
raise input_error(
|
|
294
|
+
parameter="encoding",
|
|
295
|
+
argument=encoding,
|
|
296
|
+
message="is not ASCII-compatible, as a text file format requires",
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
@overload
|
|
301
|
+
def deliver_text(
|
|
302
|
+
chunks: Iterable[str],
|
|
303
|
+
target: None = None,
|
|
304
|
+
*,
|
|
305
|
+
encoding: str = "utf-8",
|
|
306
|
+
input_error: type[InputError] | None = None,
|
|
307
|
+
) -> str: ...
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
@overload
|
|
311
|
+
def deliver_text(
|
|
312
|
+
chunks: Iterable[str],
|
|
313
|
+
target: Callable[[str], object] | str | os.PathLike[str],
|
|
314
|
+
*,
|
|
315
|
+
encoding: str = "utf-8",
|
|
316
|
+
input_error: type[InputError] | None = None,
|
|
317
|
+
) -> None: ...
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def deliver_text(
|
|
321
|
+
chunks: Iterable[str],
|
|
322
|
+
target: TextTarget = None,
|
|
323
|
+
*,
|
|
324
|
+
encoding: str = "utf-8",
|
|
325
|
+
input_error: type[InputError] | None = None,
|
|
326
|
+
) -> str | None:
|
|
327
|
+
"""Deliver text output to a target.
|
|
328
|
+
|
|
329
|
+
Parameters
|
|
330
|
+
----------
|
|
331
|
+
chunks
|
|
332
|
+
The output, in chunks whose concatenation is the whole output.
|
|
333
|
+
target
|
|
334
|
+
`None` returns the output.
|
|
335
|
+
A callable receives the non-empty chunks in order.
|
|
336
|
+
A path (a string or `os.PathLike`) receives the output as a file,
|
|
337
|
+
with its line endings unchanged. An existing file is replaced only
|
|
338
|
+
once the output is written whole, and keeps its mode; a hard link to
|
|
339
|
+
it keeps the old content. A target that is no regular file, a file
|
|
340
|
+
of another user, and a file beside which no file can be made, as in
|
|
341
|
+
a read-only folder, are written in place.
|
|
342
|
+
encoding
|
|
343
|
+
Encoding of a file that a path receives.
|
|
344
|
+
input_error
|
|
345
|
+
The exception that a rejected argument raises, the package's own;
|
|
346
|
+
`None` for `InputError`.
|
|
347
|
+
|
|
348
|
+
Returns
|
|
349
|
+
-------
|
|
350
|
+
The output if ``target`` is `None`, otherwise `None`.
|
|
351
|
+
|
|
352
|
+
Raises
|
|
353
|
+
------
|
|
354
|
+
InputError
|
|
355
|
+
If the target is of no supported type, or the encoding is unknown,
|
|
356
|
+
not ASCII-compatible, or cannot encode the output.
|
|
357
|
+
PermissionError
|
|
358
|
+
If the target is a file that cannot be written.
|
|
359
|
+
"""
|
|
360
|
+
input_error = input_error or InputError
|
|
361
|
+
check_encoding(encoding, input_error=input_error)
|
|
362
|
+
write = partial(_write_text, encoding=encoding, input_error=input_error)
|
|
363
|
+
return _deliver(chunks, target, "", write, input_error)
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
@overload
|
|
367
|
+
def deliver_bytes(
|
|
368
|
+
chunks: Iterable[bytes],
|
|
369
|
+
target: None = None,
|
|
370
|
+
*,
|
|
371
|
+
input_error: type[InputError] | None = None,
|
|
372
|
+
) -> bytes: ...
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
@overload
|
|
376
|
+
def deliver_bytes(
|
|
377
|
+
chunks: Iterable[bytes],
|
|
378
|
+
target: Callable[[bytes], object] | str | os.PathLike[str],
|
|
379
|
+
*,
|
|
380
|
+
input_error: type[InputError] | None = None,
|
|
381
|
+
) -> None: ...
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def deliver_bytes(
|
|
385
|
+
chunks: Iterable[bytes],
|
|
386
|
+
target: BinaryTarget = None,
|
|
387
|
+
*,
|
|
388
|
+
input_error: type[InputError] | None = None,
|
|
389
|
+
) -> bytes | None:
|
|
390
|
+
"""Deliver binary output to a target.
|
|
391
|
+
|
|
392
|
+
Parameters
|
|
393
|
+
----------
|
|
394
|
+
chunks
|
|
395
|
+
The output, in chunks whose concatenation is the whole output.
|
|
396
|
+
target
|
|
397
|
+
`None` returns the output, holding about one copy of it at a time;
|
|
398
|
+
a single chunk is returned without a copy.
|
|
399
|
+
A callable receives the non-empty chunks in order.
|
|
400
|
+
A path (a string or `os.PathLike`) receives the output as a file.
|
|
401
|
+
An existing file is replaced only once the output is written whole,
|
|
402
|
+
and keeps its mode; a hard link to it keeps the old content. A
|
|
403
|
+
target that is no regular file, a file of another user, and a file
|
|
404
|
+
beside which no file can be made, as in a read-only folder, are
|
|
405
|
+
written in place.
|
|
406
|
+
input_error
|
|
407
|
+
The exception that a rejected argument raises, the package's own;
|
|
408
|
+
`None` for `InputError`.
|
|
409
|
+
|
|
410
|
+
Returns
|
|
411
|
+
-------
|
|
412
|
+
The output if ``target`` is `None`, otherwise `None`.
|
|
413
|
+
|
|
414
|
+
Raises
|
|
415
|
+
------
|
|
416
|
+
InputError
|
|
417
|
+
If the target is of no supported type.
|
|
418
|
+
PermissionError
|
|
419
|
+
If the target is a file that cannot be written.
|
|
420
|
+
"""
|
|
421
|
+
input_error = input_error or InputError
|
|
422
|
+
if target is None:
|
|
423
|
+
return _joined(chunks)
|
|
424
|
+
return _deliver(chunks, target, b"", _write_bytes, input_error)
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _joined(chunks: Iterable[bytes]) -> bytes:
|
|
428
|
+
"""Return chunks as one, holding about one copy of the output at a time.
|
|
429
|
+
|
|
430
|
+
The chunks are written into a buffer as they come, whose bytes are
|
|
431
|
+
returned without a copy, so that the chunks are never all held beside
|
|
432
|
+
the output, as `bytes.join` holds them. A single chunk is returned as
|
|
433
|
+
it is.
|
|
434
|
+
"""
|
|
435
|
+
iterator = iter(chunks)
|
|
436
|
+
first = next(iterator, b"")
|
|
437
|
+
second = next(iterator, None)
|
|
438
|
+
if second is None:
|
|
439
|
+
return first
|
|
440
|
+
buffer = io.BytesIO()
|
|
441
|
+
buffer.write(first)
|
|
442
|
+
buffer.write(second)
|
|
443
|
+
del first, second
|
|
444
|
+
for chunk in iterator:
|
|
445
|
+
buffer.write(chunk)
|
|
446
|
+
return buffer.getvalue()
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _deliver[T: (str, bytes)](
|
|
450
|
+
chunks: Iterable[T],
|
|
451
|
+
target: Callable[[T], object] | str | os.PathLike[str] | None,
|
|
452
|
+
empty: T,
|
|
453
|
+
write: Callable[[Path, Iterable[T]], None],
|
|
454
|
+
input_error: type[InputError],
|
|
455
|
+
) -> T | None:
|
|
456
|
+
"""Deliver output to a target; `empty` joins it, `write` writes a file."""
|
|
457
|
+
if target is None:
|
|
458
|
+
return empty.join(chunks)
|
|
459
|
+
if isinstance(target, str | os.PathLike):
|
|
460
|
+
write(Path(target), chunks)
|
|
461
|
+
return None
|
|
462
|
+
if callable(target):
|
|
463
|
+
for chunk in chunks:
|
|
464
|
+
if chunk:
|
|
465
|
+
target(chunk)
|
|
466
|
+
return None
|
|
467
|
+
raise input_error(
|
|
468
|
+
parameter="target",
|
|
469
|
+
argument=target,
|
|
470
|
+
message="is neither None, a callable, nor a path",
|
|
471
|
+
)
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _write_text(
|
|
475
|
+
path: Path,
|
|
476
|
+
chunks: Iterable[str],
|
|
477
|
+
*,
|
|
478
|
+
encoding: str,
|
|
479
|
+
input_error: type[InputError],
|
|
480
|
+
) -> None:
|
|
481
|
+
"""Write text to a file, and reject an encoding that cannot encode it."""
|
|
482
|
+
|
|
483
|
+
def write(stream: BinaryIO) -> None:
|
|
484
|
+
encoder = codecs.getincrementalencoder(encoding)()
|
|
485
|
+
try:
|
|
486
|
+
stream.writelines(map(encoder.encode, chunks))
|
|
487
|
+
stream.write(encoder.encode("", final=True))
|
|
488
|
+
except UnicodeEncodeError as error:
|
|
489
|
+
shown = describe(error.object[error.start : error.end])
|
|
490
|
+
raise input_error(
|
|
491
|
+
parameter="encoding",
|
|
492
|
+
argument=encoding,
|
|
493
|
+
message=f"cannot encode {shown} of the output",
|
|
494
|
+
) from None
|
|
495
|
+
|
|
496
|
+
_write_file(path, write)
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def _write_bytes(path: Path, chunks: Iterable[bytes]) -> None:
|
|
500
|
+
"""Write bytes to a file."""
|
|
501
|
+
_write_file(path, lambda stream: stream.writelines(chunks))
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def _write_file(path: Path, write: Callable[[BinaryIO], None]) -> None:
|
|
505
|
+
"""Write a file, which replaces an old one only once it is complete.
|
|
506
|
+
|
|
507
|
+
The output goes to a new file beside the target, with the mode of the
|
|
508
|
+
target or of a new file, which takes the place of the target when it is
|
|
509
|
+
written, so that a failure leaves the target as it was. A hard link to
|
|
510
|
+
the target keeps the old content. The target is written in place, as
|
|
511
|
+
`open` writes it, when it is no regular file, such as a device or a
|
|
512
|
+
pipe, when it belongs to another user, whom it keeps as its owner, or
|
|
513
|
+
when no new file can be made beside it, as in a read-only folder or for
|
|
514
|
+
a name too long for another.
|
|
515
|
+
|
|
516
|
+
Raises
|
|
517
|
+
------
|
|
518
|
+
PermissionError
|
|
519
|
+
If the target is a file that cannot be written.
|
|
520
|
+
"""
|
|
521
|
+
target = Path(os.path.realpath(path))
|
|
522
|
+
try:
|
|
523
|
+
status: os.stat_result | None = target.stat()
|
|
524
|
+
except FileNotFoundError:
|
|
525
|
+
status = None
|
|
526
|
+
if status is not None and stat.S_ISREG(status.st_mode):
|
|
527
|
+
if not os.access(target, os.W_OK):
|
|
528
|
+
raise PermissionError(
|
|
529
|
+
errno.EACCES, os.strerror(errno.EACCES), str(path)
|
|
530
|
+
)
|
|
531
|
+
foreign = hasattr(os, "geteuid") and status.st_uid != os.geteuid()
|
|
532
|
+
temporary = None if foreign else _temporary(target, status)
|
|
533
|
+
elif status is None:
|
|
534
|
+
temporary = _temporary(target, None)
|
|
535
|
+
else:
|
|
536
|
+
temporary = None
|
|
537
|
+
if temporary is None:
|
|
538
|
+
with target.open("wb") as stream:
|
|
539
|
+
write(stream)
|
|
540
|
+
return
|
|
541
|
+
name, descriptor = temporary
|
|
542
|
+
try:
|
|
543
|
+
with os.fdopen(descriptor, "wb") as stream:
|
|
544
|
+
write(stream)
|
|
545
|
+
name.replace(target)
|
|
546
|
+
except BaseException:
|
|
547
|
+
name.unlink(missing_ok=True)
|
|
548
|
+
raise
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def _temporary(
|
|
552
|
+
target: Path, status: os.stat_result | None
|
|
553
|
+
) -> tuple[Path, int] | None:
|
|
554
|
+
"""Create a new file beside a target, with the mode that it will have.
|
|
555
|
+
|
|
556
|
+
A file that will replace another is made readable by its owner alone,
|
|
557
|
+
and then given the mode of the other, before anything is written to it;
|
|
558
|
+
one that makes a new file has the mode of a new file from the start.
|
|
559
|
+
|
|
560
|
+
Returns
|
|
561
|
+
-------
|
|
562
|
+
Its path and open descriptor, or `None` if no file can be made there.
|
|
563
|
+
"""
|
|
564
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0)
|
|
565
|
+
initial = _NEW_FILE_MODE if status is None else _PRIVATE_MODE
|
|
566
|
+
for _ in range(_TEMPORARY_ATTEMPTS):
|
|
567
|
+
name = target.with_name(f".{target.name}.{secrets.token_hex(4)}.tmp")
|
|
568
|
+
try:
|
|
569
|
+
descriptor = os.open(name, flags, initial)
|
|
570
|
+
except FileExistsError:
|
|
571
|
+
continue
|
|
572
|
+
except OSError:
|
|
573
|
+
return None
|
|
574
|
+
if status is not None:
|
|
575
|
+
try:
|
|
576
|
+
name.chmod(stat.S_IMODE(status.st_mode))
|
|
577
|
+
except OSError:
|
|
578
|
+
os.close(descriptor)
|
|
579
|
+
name.unlink(missing_ok=True)
|
|
580
|
+
return None
|
|
581
|
+
return name, descriptor
|
|
582
|
+
return None
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
def _ascii_compatible(encoding: str) -> bool:
|
|
586
|
+
"""Return whether an encoding reads and writes ASCII as ASCII does."""
|
|
587
|
+
text = _ASCII.decode("ascii")
|
|
588
|
+
try:
|
|
589
|
+
return (
|
|
590
|
+
_ASCII.decode(encoding) == text and text.encode(encoding) == _ASCII
|
|
591
|
+
)
|
|
592
|
+
except (LookupError, UnicodeError):
|
|
593
|
+
return False
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def _names_file(text: str) -> bool:
|
|
597
|
+
"""Return whether a string is the path of an existing file."""
|
|
598
|
+
if len(text) > _MAX_PATH_CHARACTERS or "\n" in text:
|
|
599
|
+
return False
|
|
600
|
+
try:
|
|
601
|
+
return Path(text).is_file()
|
|
602
|
+
except (OSError, ValueError):
|
|
603
|
+
return False
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def _binary(
|
|
607
|
+
file: FileLike, *, encoding: str, input_error: type[InputError]
|
|
608
|
+
) -> BinarySource:
|
|
609
|
+
"""Return the bytes of an input, decompressing gzip.
|
|
610
|
+
|
|
611
|
+
A string is a path here. `encoding` encodes the text of a stream that
|
|
612
|
+
gives text, other than a text stream of `io`.
|
|
613
|
+
"""
|
|
614
|
+
if isinstance(file, str | os.PathLike):
|
|
615
|
+
path = Path(file)
|
|
616
|
+
if not path.is_file():
|
|
617
|
+
raise input_error(
|
|
618
|
+
parameter="file",
|
|
619
|
+
argument=file,
|
|
620
|
+
message="names no existing file",
|
|
621
|
+
)
|
|
622
|
+
# Unbuffered, so that the content is read into one block of memory.
|
|
623
|
+
with path.open("rb", buffering=0) as stream:
|
|
624
|
+
compressed = stream.read(len(_GZIP_MAGIC)) == _GZIP_MAGIC
|
|
625
|
+
stream.seek(0)
|
|
626
|
+
if compressed:
|
|
627
|
+
pieces = iter(partial(stream.read, _PIECE_BYTES), b"")
|
|
628
|
+
data = _gunzip(pieces, file=file, input_error=input_error)
|
|
629
|
+
else:
|
|
630
|
+
data = stream.readall()
|
|
631
|
+
return BinarySource(data=data, path=path)
|
|
632
|
+
try:
|
|
633
|
+
data = fileex.file.content(
|
|
634
|
+
file,
|
|
635
|
+
path_can_be_str=False,
|
|
636
|
+
gzip_decompress=False,
|
|
637
|
+
output="bytes",
|
|
638
|
+
encoding=encoding,
|
|
639
|
+
)
|
|
640
|
+
except TypeError:
|
|
641
|
+
raise input_error(
|
|
642
|
+
parameter="file",
|
|
643
|
+
argument=file,
|
|
644
|
+
message="is no file input: a path, content, or a readable stream",
|
|
645
|
+
) from None
|
|
646
|
+
except UnicodeEncodeError:
|
|
647
|
+
raise input_error(
|
|
648
|
+
parameter="file",
|
|
649
|
+
argument=file,
|
|
650
|
+
message=f"holds text that the encoding {encoding!r} cannot encode",
|
|
651
|
+
) from None
|
|
652
|
+
if data.startswith(_GZIP_MAGIC):
|
|
653
|
+
data = _gunzip(_pieces(data), file=file, input_error=input_error)
|
|
654
|
+
return BinarySource(data=data, path=None)
|
|
655
|
+
|
|
656
|
+
|
|
657
|
+
def _pieces(data: bytes) -> Iterator[memoryview]:
|
|
658
|
+
"""Yield bytes in pieces, without copies."""
|
|
659
|
+
view = memoryview(data)
|
|
660
|
+
for start in range(0, len(view), _PIECE_BYTES):
|
|
661
|
+
yield view[start : start + _PIECE_BYTES]
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
def _gunzip(
|
|
665
|
+
pieces: Iterable[bytes | memoryview],
|
|
666
|
+
*,
|
|
667
|
+
file: object,
|
|
668
|
+
input_error: type[InputError],
|
|
669
|
+
) -> bytes:
|
|
670
|
+
"""Decompress gzip, given in pieces, member by member.
|
|
671
|
+
|
|
672
|
+
The output grows in place and is returned without a copy, so that the
|
|
673
|
+
peak memory is the output and a piece. Zero bytes may pad the members,
|
|
674
|
+
as gzip allows.
|
|
675
|
+
"""
|
|
676
|
+
output = io.BytesIO()
|
|
677
|
+
decompressor = zlib.decompressobj(wbits=_GZIP_WBITS)
|
|
678
|
+
for piece in pieces:
|
|
679
|
+
data: bytes | memoryview = piece
|
|
680
|
+
while data:
|
|
681
|
+
if decompressor.eof:
|
|
682
|
+
data = bytes(data).lstrip(b"\x00")
|
|
683
|
+
if not data:
|
|
684
|
+
break
|
|
685
|
+
decompressor = zlib.decompressobj(wbits=_GZIP_WBITS)
|
|
686
|
+
try:
|
|
687
|
+
output.write(decompressor.decompress(data, _PIECE_BYTES))
|
|
688
|
+
except zlib.error as error:
|
|
689
|
+
raise input_error(
|
|
690
|
+
parameter="file",
|
|
691
|
+
argument=file,
|
|
692
|
+
message=f"holds corrupt gzip-compressed data: {error}",
|
|
693
|
+
) from None
|
|
694
|
+
data = (
|
|
695
|
+
decompressor.unused_data
|
|
696
|
+
if decompressor.eof
|
|
697
|
+
else decompressor.unconsumed_tail
|
|
698
|
+
)
|
|
699
|
+
if not decompressor.eof:
|
|
700
|
+
raise input_error(
|
|
701
|
+
parameter="file",
|
|
702
|
+
argument=file,
|
|
703
|
+
message="ends within its gzip-compressed data",
|
|
704
|
+
)
|
|
705
|
+
return output.getvalue()
|