| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
__all__ = ( |
| 4 |
"FileReadStream", |
| 5 |
"FileStreamAttribute", |
| 6 |
"FileWriteStream", |
| 7 |
) |
| 8 |
|
| 9 |
from collections.abc import Callable, Mapping |
| 10 |
from io import SEEK_SET, UnsupportedOperation |
| 11 |
from os import PathLike |
| 12 |
from pathlib import Path |
| 13 |
from typing import Any, BinaryIO, cast |
| 14 |
|
| 15 |
from .. import ( |
| 16 |
BrokenResourceError, |
| 17 |
ClosedResourceError, |
| 18 |
EndOfStream, |
| 19 |
TypedAttributeSet, |
| 20 |
to_thread, |
| 21 |
typed_attribute, |
| 22 |
) |
| 23 |
from ..abc import ByteReceiveStream, ByteSendStream |
| 24 |
|
| 25 |
|
| 26 |
class FileStreamAttribute(TypedAttributeSet): |
| 27 |
#: the open file descriptor |
| 28 |
file: BinaryIO = typed_attribute() |
| 29 |
#: the path of the file on the file system, if available (file must be a real file) |
| 30 |
path: Path = typed_attribute() |
| 31 |
#: the file number, if available (file must be a real file or a TTY) |
| 32 |
fileno: int = typed_attribute() |
| 33 |
|
| 34 |
|
| 35 |
class _BaseFileStream: |
| 36 |
def __init__(self, file: BinaryIO): |
| 37 |
self._file = file |
| 38 |
|
| 39 |
async def aclose(self) -> None: |
| 40 |
await to_thread.run_sync(self._file.close) |
| 41 |
|
| 42 |
@property |
| 43 |
def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: |
| 44 |
attributes: dict[Any, Callable[[], Any]] = { |
| 45 |
FileStreamAttribute.file: lambda: self._file, |
| 46 |
} |
| 47 |
|
| 48 |
if hasattr(self._file, "name"): |
| 49 |
attributes[FileStreamAttribute.path] = lambda: Path(self._file.name) |
| 50 |
|
| 51 |
try: |
| 52 |
self._file.fileno() |
| 53 |
except UnsupportedOperation: |
| 54 |
pass |
| 55 |
else: |
| 56 |
attributes[FileStreamAttribute.fileno] = lambda: self._file.fileno() |
| 57 |
|
| 58 |
return attributes |
| 59 |
|
| 60 |
|
| 61 |
class FileReadStream(_BaseFileStream, ByteReceiveStream): |
| 62 |
""" |
| 63 |
A byte stream that reads from a file in the file system. |
| 64 |
|
| 65 |
:param file: a file that has been opened for reading in binary mode |
| 66 |
|
| 67 |
.. versionadded:: 3.0 |
| 68 |
""" |
| 69 |
|
| 70 |
@classmethod |
| 71 |
async def from_path(cls, path: str | PathLike[str]) -> FileReadStream: |
| 72 |
""" |
| 73 |
Create a file read stream by opening the given file. |
| 74 |
|
| 75 |
:param path: path of the file to read from |
| 76 |
|
| 77 |
""" |
| 78 |
file = await to_thread.run_sync(Path(path).open, "rb") |
| 79 |
return cls(cast(BinaryIO, file)) |
| 80 |
|
| 81 |
async def receive(self, max_bytes: int = 65536) -> bytes: |
| 82 |
try: |
| 83 |
data = await to_thread.run_sync(self._file.read, max_bytes) |
| 84 |
except ValueError: |
| 85 |
raise ClosedResourceError from None |
| 86 |
except OSError as exc: |
| 87 |
raise BrokenResourceError from exc |
| 88 |
|
| 89 |
if data: |
| 90 |
return data |
| 91 |
else: |
| 92 |
raise EndOfStream |
| 93 |
|
| 94 |
async def seek(self, position: int, whence: int = SEEK_SET) -> int: |
| 95 |
""" |
| 96 |
Seek the file to the given position. |
| 97 |
|
| 98 |
.. seealso:: :meth:`io.IOBase.seek` |
| 99 |
|
| 100 |
.. note:: Not all file descriptors are seekable. |
| 101 |
|
| 102 |
:param position: position to seek the file to |
| 103 |
:param whence: controls how ``position`` is interpreted |
| 104 |
:return: the new absolute position |
| 105 |
:raises OSError: if the file is not seekable |
| 106 |
|
| 107 |
""" |
| 108 |
return await to_thread.run_sync(self._file.seek, position, whence) |
| 109 |
|
| 110 |
async def tell(self) -> int: |
| 111 |
""" |
| 112 |
Return the current stream position. |
| 113 |
|
| 114 |
.. note:: Not all file descriptors are seekable. |
| 115 |
|
| 116 |
:return: the current absolute position |
| 117 |
:raises OSError: if the file is not seekable |
| 118 |
|
| 119 |
""" |
| 120 |
return await to_thread.run_sync(self._file.tell) |
| 121 |
|
| 122 |
|
| 123 |
class FileWriteStream(_BaseFileStream, ByteSendStream): |
| 124 |
""" |
| 125 |
A byte stream that writes to a file in the file system. |
| 126 |
|
| 127 |
:param file: a file that has been opened for writing in binary mode |
| 128 |
|
| 129 |
.. versionadded:: 3.0 |
| 130 |
""" |
| 131 |
|
| 132 |
@classmethod |
| 133 |
async def from_path( |
| 134 |
cls, path: str | PathLike[str], append: bool = False |
| 135 |
) -> FileWriteStream: |
| 136 |
""" |
| 137 |
Create a file write stream by opening the given file for writing. |
| 138 |
|
| 139 |
:param path: path of the file to write to |
| 140 |
:param append: if ``True``, open the file for appending; if ``False``, any |
| 141 |
existing file at the given path will be truncated |
| 142 |
|
| 143 |
""" |
| 144 |
mode = "ab" if append else "wb" |
| 145 |
file = await to_thread.run_sync(Path(path).open, mode) |
| 146 |
return cls(cast(BinaryIO, file)) |
| 147 |
|
| 148 |
async def send(self, item: bytes) -> None: |
| 149 |
try: |
| 150 |
await to_thread.run_sync(self._file.write, item) |
| 151 |
except ValueError: |
| 152 |
raise ClosedResourceError from None |
| 153 |
except OSError as exc: |
| 154 |
raise BrokenResourceError from exc |