Debian Codegraph @

DisplayCAL/util_io.py

raw
1 """Utility classes and functions for file I/O.
2
3 It includes tools for encoding/decoding data during file writes, managing
4 multiple file objects, working with GZIP and TAR files, buffering line-based
5 streams, and other file-related utilities.
6 """
7
8 from __future__ import annotations
9
10 import contextlib
11 import copy
12 import gzip
13 import operator
14 import os
15 import sys
16 import tarfile
17 from io import StringIO
18 from time import time
19 from typing import TYPE_CHECKING, Any, BinaryIO, TextIO
20
21 # from safe_print import safe_print
22 from DisplayCAL.util_str import universal_newlines
23
24 if TYPE_CHECKING:
25 from collections.abc import Iterator
26 from types import TracebackType
27
28 if sys.version_info >= (3, 11):
29 from typing import Self
30 else:
31 from typing_extensions import Self
32
33
34 class EncodedWriter:
35 """Encodes data before writing it to a file object.
36
37 Either data_encoding or file_encoding can be None.
38
39 Args:
40 file_obj (BinaryIO | TextIO): The file object to write to.
41 data_encoding (str, optional): The encoding to use for decoding data
42 before writing. Defaults to None.
43 file_encoding (str, optional): The encoding to use for encoding data
44 before writing. Defaults to None.
45 errors (str, optional): The error handling scheme to use for encoding
46 and decoding errors. Defaults to "replace".
47 """
48
49 def __init__(
50 self,
51 file_obj: BinaryIO | TextIO,
52 data_encoding: str | None = None,
53 file_encoding: str | None = None,
54 errors: str = "replace",
55 ) -> None:
56 self.file = file_obj
57 self.data_encoding = data_encoding
58 self.file_encoding = file_encoding
59 self.errors = errors
60
61 def __getattr__(self, name: str) -> Any: # noqa: ANN401
62 """Get attribute from the file object.
63
64 Args:
65 name (str): The name of the attribute to get.
66
67 Returns:
68 Any: The value of the attribute from the file object.
69 """
70 return getattr(self.file, name)
71
72 def write(self, data: str | bytes | bytearray) -> None:
73 """Write data to the file.
74
75 First decoding it with data_encoding and encoding it with file_encoding
76 if specified.
77
78 Args:
79 data (str | bytes | bytearray): The data to write to the file.
80 """
81 if self.data_encoding and not isinstance(data, str):
82 data = data.decode(self.data_encoding, self.errors)
83 if self.file_encoding and isinstance(data, str):
84 data = data.encode(self.file_encoding, self.errors)
85 self.file.write(data.decode())
86
87
88 class Files:
89 """Read and/or write from/to several files at once.
90
91 Args:
92 files (list[str] | list[BinaryIO | TextIO]): files must be a list or
93 tuple of file objects or filenames (the mode parameter is only used
94 in the latter case).
95 """
96
97 def __init__(
98 self, files: list[str] | list[BinaryIO | TextIO], mode: str = "r"
99 ) -> None:
100 self.files = []
101 for item in files:
102 if isinstance(item, str):
103 self.files.append(open(item, mode)) # noqa: SIM115
104 else:
105 self.files.append(item)
106
107 def __iter__(self) -> Iterator:
108 """Return an iterator over the files in the Files object.
109
110 Returns:
111 iterator: An iterator over the files in the Files object.
112 """
113 return iter(self.files)
114
115 def close(self) -> None:
116 """Close all files in the Files object."""
117 for item in self.files:
118 item.close()
119
120 def flush(self) -> None:
121 """Flush all files."""
122 for item in self.files:
123 with contextlib.suppress(AttributeError):
124 # TODO: Restore safe_log
125 item.flush()
126
127 def seek(self, pos: int, mode: int = 0) -> None:
128 """Seek to a position in all files.
129
130 Args:
131 pos (int): The position to seek to.
132 mode (int, optional): The mode for seeking. Defaults to 0 (absolute
133 file positioning). Other values are 1 (relative to current
134 position) and 2 (relative to file's end).
135 """
136 for item in self.files:
137 item.seek(pos, mode)
138
139 def truncate(self, size: None | int = None) -> None:
140 """Truncate all files to the specified size.
141
142 Args:
143 size (None | int, optional): The size to truncate the files to. If
144 None, the files are truncated to the current position. Defaults
145 to None.
146 """
147 for item in self.files:
148 item.truncate(size)
149
150 def write(self, data: str | bytes | bytearray) -> None:
151 """Write data to all files.
152
153 Args:
154 data (str | bytes | bytearray): The data to write to the files.
155 """
156 for item in self.files:
157 try:
158 item.write(data)
159 except AttributeError: # TODO: restore safe_log, safe_print etc...
160 with contextlib.suppress(TypeError):
161 item(data)
162
163 def writelines(self, str_sequence: list[str]) -> None:
164 """Write a sequence of strings to all files.
165
166 Args:
167 str_sequence (list[str]): A sequence of strings to write to the files.
168 """
169 self.write("".join(str_sequence))
170
171
172 class GzipFileProper(gzip.GzipFile):
173 """Proper GZIP file implementation.
174
175 Where the optional filename in the header has directory components removed,
176 and is converted to ISO 8859-1 (Latin-1). On Windows, the filename will
177 also be forced to lowercase.
178
179 See RFC 1952 GZIP File Format Specification version 4.3
180 """
181
182 def _write_gzip_header(self, compresslevel: int) -> None:
183 """Write the GZIP file header.
184
185 Args:
186 compresslevel (int): The compression level to use.
187 """
188 self.fileobj.write(b"\037\213") # magic header
189 self.fileobj.write(b"\010") # compression method
190 fname = os.path.basename(self.name)
191 if fname.endswith(".gz"):
192 fname = fname[:-3]
193 elif fname.endswith(".tgz"):
194 fname = f"{fname[:-4]}.tar"
195 elif fname.endswith(".wrz"):
196 fname = f"{fname[:-4]}.wrl"
197 flags = 0
198 if fname:
199 flags = gzip.FNAME
200 self.fileobj.write(chr(flags).encode())
201 gzip.write32u(self.fileobj, int(time()))
202 self.fileobj.write(b"\002")
203 self.fileobj.write(b"\377")
204 if fname:
205 if sys.platform == "win32":
206 # Windows is case insensitive by default (although it can be
207 # set to case sensitive), so according to the GZIP spec, we
208 # force the name to lowercase
209 fname = fname.lower()
210 self.fileobj.write(
211 fname.encode("ISO-8859-1", "replace").replace(b"?", b"_") + b"\000"
212 )
213
214 def __enter__(self) -> Self:
215 """Enter the runtime context related to this object.
216
217 Returns:
218 GzipFileProper: The GzipFileProper object itself.
219 """
220 return self
221
222 def __exit__(
223 self,
224 exc_type: None | type[BaseException],
225 exc_value: None | BaseException,
226 tb: None | TracebackType,
227 ) -> None:
228 """Exit the runtime context related to this object.
229
230 Args:
231 exc_type: The exception type.
232 exc_value: The exception value.
233 tb: The traceback object.
234
235 Returns:
236 None: No return value.
237 """
238 self.close()
239
240
241 class LineBufferedStream:
242 """Buffer lines and only write them to stream if line separator is detected."""
243
244 def __init__(
245 self,
246 stream: TextIO | BinaryIO,
247 data_encoding: None | str = None,
248 file_encoding: None | str = None,
249 errors: str = "replace",
250 linesep_in: str = "\r\n",
251 linesep_out: str = "",
252 ) -> None:
253 self.buf = ""
254 self.data_encoding = data_encoding
255 self.file_encoding = file_encoding
256 self.errors = errors
257 self.linesep_in = linesep_in
258 self.linesep_out = linesep_out
259 self.stream = stream
260
261 def __del__(self) -> None:
262 """Destructor to ensure the stream is closed properly."""
263 self.commit()
264
265 def __getattr__(self, name: str) -> Any: # noqa: ANN401
266 """Get attribute from the stream.
267
268 Args:
269 name (str): The name of the attribute to get.
270
271 Returns:
272 Any: The value of the attribute from the stream.
273 """
274 return getattr(self.stream, name)
275
276 def close(self) -> None:
277 """Close the stream and commit any buffered data."""
278 self.commit()
279 self.stream.close()
280
281 def commit(self) -> None:
282 """Write the buffered data to the stream, encoding it if necessary."""
283 if not self.buf:
284 return
285 if self.data_encoding and isinstance(self.buf, bytes):
286 self.buf = self.buf.decode(self.data_encoding, self.errors)
287 if self.file_encoding:
288 self.buf = self.buf.encode(self.file_encoding, self.errors)
289 self.stream.write(self.buf)
290 self.buf = ""
291
292 def write(self, data: str | bytes | bytearray) -> None:
293 """Write data to the stream, buffering it until a line separator is detected.
294
295 Args:
296 data (str | bytes | bytearray): The data to write to the stream.
297
298 Raises:
299 TypeError: If the data is not of type str, bytes, or bytearray.
300 """
301 if isinstance(data, (bytes, bytearray)):
302 data = data.decode()
303 if not isinstance(data, str):
304 raise TypeError(
305 f"Expected str, bytes or bytearray, got {type(data).__name__}"
306 )
307 data = data.replace(self.linesep_in, "\n")
308 for char in data:
309 if char == "\r":
310 while self.buf and not self.buf.endswith("\n"):
311 self.buf = self.buf[:-1]
312 elif char == "\n":
313 self.buf += self.linesep_out
314 self.commit()
315 else:
316 self.buf += char
317
318
319 class LineCache:
320 """A simple line cache that stores the last n + 1 lines written to it.
321
322 And returns only the last n non-empty lines when read.
323
324 Args:
325 maxlines (int): The maximum number of lines to keep in the cache.
326 Defaults to 1.
327 """
328
329 def __init__(self, maxlines: int = 1) -> None:
330 self.clear()
331 self.maxlines = maxlines
332
333 def clear(self) -> None:
334 """Clear the cache, resetting it to an empty state."""
335 self.cache = [""]
336
337 def flush(self) -> None:
338 """Flush the cache, clearing it."""
339
340 def read(self, triggers: None | list[str] = None) -> str:
341 """Read cached lines, excluding those containing any triggers.
342
343 Args:
344 triggers (list of str, optional): A list of strings to filter out
345 lines that contain them. If None, no filtering is applied.
346
347 Returns:
348 str: The last n non-empty lines from the cache, joined by newlines.
349 """
350 lines = [""]
351 for line in self.cache:
352 read = True
353 if triggers:
354 for trigger in triggers:
355 if trigger.lower() in line.lower():
356 read = False
357 break
358 if read and line:
359 lines.append(line)
360 return "\n".join([line for line in lines if line][-self.maxlines :])
361
362 def write(self, data: str) -> None:
363 """Write data to the cache, splitting it into lines and handling line endings.
364
365 Args:
366 data (str): The data to write to the cache.
367 """
368 cache = list(self.cache)
369 for char in data:
370 if char == "\r":
371 cache[-1] = ""
372 elif char == "\n":
373 cache.append("")
374 else:
375 cache[-1] += char
376 self.cache = ([line for line in cache[:-1] if line] + cache[-1:])[
377 -self.maxlines - 1 :
378 ]
379
380
381 class StringIOu(StringIO):
382 """StringIO which converts all new line formats in buf to POSIX newlines."""
383
384 def __init__(self, buf: str = "") -> None:
385 StringIO.__init__(self, universal_newlines(buf))
386
387
388 class Tee(Files):
389 """Write to a file and stdout.
390
391 Args:
392 file_obj (file-like object): The file object to write to.
393 """
394
395 def __init__(self, file_obj: TextIO | BinaryIO) -> None:
396 Files.__init__((sys.stdout, file_obj))
397
398 def __getattr__(self, name: str) -> Any: # noqa: ANN401
399 """Get attribute from the second file object.
400
401 Args:
402 name (str): The name of the attribute to get.
403
404 Returns:
405 Any: The value of the attribute from the second file object.
406 """
407 return getattr(self.files[1], name)
408
409 def close(self) -> None:
410 """Close the second file object."""
411 self.files[1].close()
412
413 def seek(self, pos: int, mode: int = 0) -> int:
414 """Seek to a position in the second file.
415
416 Args:
417 pos (int): The position to seek to.
418 mode (int, optional): The mode for seeking. Defaults to 0 (absolute
419 file positioning).
420
421 Returns:
422 int: The new position in the second file after seeking.
423 """
424 return self.files[1].seek(pos, mode)
425
426 def truncate(self, size: None | int = None) -> int:
427 """Truncate the second file to the specified size.
428
429 Args:
430 size (int, optional): The size to truncate the file to. If None,
431 the file is truncated to the current position. Defaults to
432 None.
433
434 Returns:
435 int: The new size of the second file after truncation.
436 """
437 return self.files[1].truncate(size)
438
439
440 class TarFileProper(tarfile.TarFile):
441 """Support extracting to unicode location and using base name."""
442
443 def extract(
444 self, member: str | tarfile.TarInfo, path: str = "", full: bool = True
445 ) -> None:
446 """Extract a member from the archive to the current working directory.
447
448 The full name or base name of the extracted files are used. Its file
449 information is extracted as accurately as possible.
450
451 Args:
452 member (str | TarInfo): The name of the member to extract or a
453 TarInfo object representing the member.
454 path (str, optional): The directory to extract to. Defaults to the
455 current working directory ("").
456 full (bool, optional): If True, use the full path for extraction.
457 If False, use only the base name of the member. Defaults to
458 True.
459
460 Raises:
461 OSError: If there is an error during extraction.
462 tarfile.ExtractError: If there is an error extracting the member.
463 """
464 self._check("r")
465 tarinfo = self.getmember(member) if isinstance(member, str) else member
466
467 # Prepare the link target for makelink().
468 if tarinfo.islnk():
469 name = tarinfo.linkname.decode(self.encoding)
470 if not full:
471 name = os.path.basename(name)
472 tarinfo._link_target = os.path.join(path, name)
473
474 try:
475 name = tarinfo.name
476 if not full:
477 name = os.path.basename(name)
478 self._extract_member(tarinfo, os.path.join(path, name))
479 except OSError as e:
480 if self.errorlevel > 0:
481 raise e
482 if e.filename is None:
483 self._dbg(1, f"tarfile: {e.strerror}")
484 else:
485 self._dbg(1, f"tarfile: {e.strerror} {e.filename!r}")
486 except tarfile.ExtractError as e:
487 if self.errorlevel > 1:
488 raise e
489 self._dbg(1, f"tarfile: {e}")
490
491 def extractall(
492 self,
493 path: str = ".",
494 members: None | list[tarfile.TarInfo] = None,
495 full: bool = True,
496 ) -> None:
497 """Extract all members from the archive to the current working directory.
498
499 Also, set owner, modification time and permissions on directories
500 afterwards.
501
502 Args:
503 path (str, optional): The directory to extract to. Defaults to the
504 current working directory (".").
505 members (list of TarInfo, optional): A list of members to extract.
506 must be a subset of the list returned by `getmembers()`. If
507 None, all members are extracted. Defaults to None.
508 full (bool, optional): If True, use the full path for extraction.
509 If False, use only the base name of the member. Defaults to
510 True.
511 """
512 directories = []
513
514 if members is None:
515 members = self
516
517 for tarinfo in members:
518 if tarinfo.isdir():
519 # Extract directories with a safe mode.
520 directories.append(tarinfo)
521 tarinfo = copy.copy(tarinfo)
522 tarinfo.mode = 0o700
523 self.extract(tarinfo, path, full)
524
525 # Reverse sort directories.
526 directories.sort(key=operator.attrgetter("name"))
527 directories.reverse()
528
529 # Set correct owner, mtime and filemode on directories.
530 for tarinfo in directories:
531 name = tarinfo.name
532 if not full:
533 name = os.path.basename(name)
534 dirpath = os.path.join(path, name)
535 try:
536 self.chown(tarinfo, dirpath, numeric_owner=False)
537 self.utime(tarinfo, dirpath)
538 self.chmod(tarinfo, dirpath)
539 except tarfile.ExtractError as e:
540 if self.errorlevel > 1:
541 raise e
542 self._dbg(1, f"tarfile: {e}")