1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
|
"""This module provides abstract base classes for CAN message reading and writing operations
to various file formats.
.. note::
All classes in this module are abstract and should be subclassed to implement
specific file format handling.
"""
import locale
import os
from abc import ABC, abstractmethod
from collections.abc import Iterable
from contextlib import AbstractContextManager
from io import BufferedIOBase, TextIOWrapper
from pathlib import Path
from types import TracebackType
from typing import (
TYPE_CHECKING,
Any,
BinaryIO,
Generic,
Literal,
Optional,
TextIO,
TypeVar,
Union,
)
from typing_extensions import Self
from ..listener import Listener
from ..message import Message
from ..typechecking import FileLike, StringPathLike
if TYPE_CHECKING:
from _typeshed import (
OpenBinaryModeReading,
OpenBinaryModeUpdating,
OpenBinaryModeWriting,
OpenTextModeReading,
OpenTextModeUpdating,
OpenTextModeWriting,
)
#: type parameter used in generic classes :class:`MessageReader` and :class:`MessageWriter`
_IoTypeVar = TypeVar("_IoTypeVar", bound=FileLike)
class MessageWriter(AbstractContextManager["MessageWriter"], Listener, ABC):
"""Abstract base class for all CAN message writers.
This class serves as a foundation for implementing different message writer formats.
It combines context manager capabilities with the message listener interface.
:param file: Path-like object or string representing the output file location
:param kwargs: Additional keyword arguments for specific writer implementations
"""
@abstractmethod
def __init__(self, file: StringPathLike, **kwargs: Any) -> None:
pass
@abstractmethod
def stop(self) -> None:
"""Stop handling messages and cleanup any resources."""
def __enter__(self) -> Self:
"""Enter the context manager."""
return self
def __exit__(
self,
exc_type: Optional[type[BaseException]],
exc_value: Optional[BaseException],
traceback: Optional[TracebackType],
) -> Literal[False]:
"""Exit the context manager and ensure proper cleanup."""
self.stop()
return False
class SizedMessageWriter(MessageWriter, ABC):
"""Abstract base class for message writers that can report their file size.
This class extends :class:`MessageWriter` with the ability to determine the size
of the output file.
"""
@abstractmethod
def file_size(self) -> int:
"""Get the current size of the output file in bytes.
:return: The size of the file in bytes
:rtype: int
"""
class FileIOMessageWriter(SizedMessageWriter, Generic[_IoTypeVar]):
"""Base class for writers that operate on file descriptors.
This class provides common functionality for writers that work with file objects.
:param file: A path-like object or file object to write to
:param kwargs: Additional keyword arguments for specific writer implementations
:ivar file: The file object being written to
"""
file: _IoTypeVar
@abstractmethod
def __init__(self, file: Union[StringPathLike, _IoTypeVar], **kwargs: Any) -> None:
pass
def stop(self) -> None:
"""Close the file and stop writing."""
self.file.close()
def file_size(self) -> int:
"""Get the current file size."""
return self.file.tell()
class TextIOMessageWriter(FileIOMessageWriter[Union[TextIO, TextIOWrapper]], ABC):
"""Text-based message writer implementation.
:param file: Text file to write to
:param mode: File open mode for text operations
:param kwargs: Additional arguments like encoding
"""
def __init__(
self,
file: Union[StringPathLike, TextIO, TextIOWrapper],
mode: "Union[OpenTextModeUpdating, OpenTextModeWriting]" = "w",
**kwargs: Any,
) -> None:
if isinstance(file, (str, os.PathLike)):
encoding: str = kwargs.get("encoding", locale.getpreferredencoding(False))
# pylint: disable=consider-using-with
self.file = Path(file).open(mode=mode, encoding=encoding)
else:
self.file = file
class BinaryIOMessageWriter(FileIOMessageWriter[Union[BinaryIO, BufferedIOBase]], ABC):
"""Binary file message writer implementation.
:param file: Binary file to write to
:param mode: File open mode for binary operations
:param kwargs: Additional implementation specific arguments
"""
def __init__(
self,
file: Union[StringPathLike, BinaryIO, BufferedIOBase],
mode: "Union[OpenBinaryModeUpdating, OpenBinaryModeWriting]" = "wb",
**kwargs: Any,
) -> None:
if isinstance(file, (str, os.PathLike)):
# pylint: disable=consider-using-with,unspecified-encoding
self.file = Path(file).open(mode=mode)
else:
self.file = file
class MessageReader(AbstractContextManager["MessageReader"], Iterable[Message], ABC):
"""Abstract base class for all CAN message readers.
This class serves as a foundation for implementing different message reader formats.
It combines context manager capabilities with iteration interface.
:param file: Path-like object or string representing the input file location
:param kwargs: Additional keyword arguments for specific reader implementations
"""
@abstractmethod
def __init__(self, file: StringPathLike, **kwargs: Any) -> None:
pass
@abstractmethod
def stop(self) -> None:
"""Stop reading messages and cleanup any resources."""
def __enter__(self) -> Self:
return self
def __exit__(
self,
exc_type: Optional[type[BaseException]],
exc_value: Optional[BaseException],
traceback: Optional[TracebackType],
) -> Literal[False]:
self.stop()
return False
class FileIOMessageReader(MessageReader, Generic[_IoTypeVar]):
"""Base class for readers that operate on file descriptors.
This class provides common functionality for readers that work with file objects.
:param file: A path-like object or file object to read from
:param kwargs: Additional keyword arguments for specific reader implementations
:ivar file: The file object being read from
"""
file: _IoTypeVar
@abstractmethod
def __init__(self, file: Union[StringPathLike, _IoTypeVar], **kwargs: Any) -> None:
pass
def stop(self) -> None:
self.file.close()
class TextIOMessageReader(FileIOMessageReader[Union[TextIO, TextIOWrapper]], ABC):
"""Text-based message reader implementation.
:param file: Text file to read from
:param mode: File open mode for text operations
:param kwargs: Additional arguments like encoding
"""
def __init__(
self,
file: Union[StringPathLike, TextIO, TextIOWrapper],
mode: "OpenTextModeReading" = "r",
**kwargs: Any,
) -> None:
if isinstance(file, (str, os.PathLike)):
encoding: str = kwargs.get("encoding", locale.getpreferredencoding(False))
# pylint: disable=consider-using-with
self.file = Path(file).open(mode=mode, encoding=encoding)
else:
self.file = file
class BinaryIOMessageReader(FileIOMessageReader[Union[BinaryIO, BufferedIOBase]], ABC):
"""Binary file message reader implementation.
:param file: Binary file to read from
:param mode: File open mode for binary operations
:param kwargs: Additional implementation specific arguments
"""
def __init__(
self,
file: Union[StringPathLike, BinaryIO, BufferedIOBase],
mode: "OpenBinaryModeReading" = "rb",
**kwargs: Any,
) -> None:
if isinstance(file, (str, os.PathLike)):
# pylint: disable=consider-using-with,unspecified-encoding
self.file = Path(file).open(mode=mode)
else:
self.file = file
|