| 1 |
import abc |
| 2 |
import asyncio |
| 3 |
import functools |
| 4 |
import io |
| 5 |
import operator |
| 6 |
import stat |
| 7 |
import sys |
| 8 |
import time |
| 9 |
from collections.abc import AsyncIterable, Awaitable, Callable, Generator, Iterator |
| 10 |
from concurrent.futures import Executor |
| 11 |
from os import stat_result |
| 12 |
from pathlib import Path, PurePath, PurePosixPath |
| 13 |
from typing import ( |
| 14 |
TYPE_CHECKING, |
| 15 |
Any, |
| 16 |
Generic, |
| 17 |
Literal, |
| 18 |
NamedTuple, |
| 19 |
Protocol, |
| 20 |
TypedDict, |
| 21 |
TypeVar, |
| 22 |
overload, |
| 23 |
) |
| 24 |
|
| 25 |
from .common import ( |
| 26 |
DEFAULT_BLOCK_SIZE, |
| 27 |
AbstractAsyncLister, |
| 28 |
AsyncStreamIterator, |
| 29 |
Connection, |
| 30 |
with_timeout, |
| 31 |
) |
| 32 |
from .errors import PathIOError |
| 33 |
|
| 34 |
if sys.version_info >= (3, 11): |
| 35 |
from typing import Concatenate, ParamSpec, Self, Unpack |
| 36 |
else: |
| 37 |
from typing import Concatenate |
| 38 |
|
| 39 |
from typing_extensions import ParamSpec, Self, Unpack |
| 40 |
|
| 41 |
|
| 42 |
if TYPE_CHECKING: |
| 43 |
from _typeshed import OpenBinaryMode, ReadableBuffer |
| 44 |
|
| 45 |
|
| 46 |
__all__ = ( |
| 47 |
"AbstractPathIO", |
| 48 |
"PathIO", |
| 49 |
"AsyncPathIO", |
| 50 |
"MemoryPathIO", |
| 51 |
"PathIONursery", |
| 52 |
) |
| 53 |
|
| 54 |
|
| 55 |
PathIOType = TypeVar("PathIOType", bound="AbstractPathIO[Any]") |
| 56 |
|
| 57 |
|
| 58 |
class _OpenKwargs(TypedDict, total=False): |
| 59 |
path: Path |
| 60 |
mode: str |
| 61 |
|
| 62 |
|
| 63 |
class AsyncPathIOContext: |
| 64 |
""" |
| 65 |
Async pathio context. |
| 66 |
|
| 67 |
Usage: |
| 68 |
:: |
| 69 |
|
| 70 |
>>> async with pathio.open(filename) as file_in: |
| 71 |
... async for block in file_in.iter_by_block(size): |
| 72 |
... # do |
| 73 |
|
| 74 |
or borring: |
| 75 |
:: |
| 76 |
|
| 77 |
>>> file = await pathio.open(filename) |
| 78 |
... data = await file.read(size) |
| 79 |
... await file.write(data) |
| 80 |
... await file.close() |
| 81 |
|
| 82 |
""" |
| 83 |
|
| 84 |
def __init__(self, pathio: PathIOType, args: tuple[Any], kwargs: _OpenKwargs) -> None: |
| 85 |
self.close: Callable[..., Awaitable[None]] | None = None |
| 86 |
self.pathio = pathio |
| 87 |
self.args = args |
| 88 |
self.kwargs = kwargs |
| 89 |
|
| 90 |
async def __aenter__(self) -> Self: |
| 91 |
self.file = await self.pathio._open(*self.args, **self.kwargs) |
| 92 |
self.seek = functools.partial(self.pathio.seek, self.file) |
| 93 |
self.write = functools.partial(self.pathio.write, self.file) |
| 94 |
self.read = functools.partial(self.pathio.read, self.file) |
| 95 |
self.close = functools.partial(self.pathio.close, self.file) |
| 96 |
|
| 97 |
return self |
| 98 |
|
| 99 |
async def __aexit__(self, *args: Any) -> None: |
| 100 |
if self.close is not None: |
| 101 |
await self.close() |
| 102 |
|
| 103 |
def __await__(self) -> Generator[None, None, Self]: |
| 104 |
return self.__aenter__().__await__() |
| 105 |
|
| 106 |
def iter_by_block(self, count: int = DEFAULT_BLOCK_SIZE) -> AsyncIterable[bytes]: |
| 107 |
return AsyncStreamIterator(lambda: self.read(count)) |
| 108 |
|
| 109 |
|
| 110 |
UniversalExceptionParamSpec = ParamSpec("UniversalExceptionParamSpec") |
| 111 |
UniversalExceptionReturnType = TypeVar("UniversalExceptionReturnType") |
| 112 |
|
| 113 |
|
| 114 |
def universal_exception( |
| 115 |
coro: Callable[UniversalExceptionParamSpec, Awaitable[UniversalExceptionReturnType]], |
| 116 |
) -> Callable[UniversalExceptionParamSpec, Awaitable[UniversalExceptionReturnType]]: |
| 117 |
""" |
| 118 |
Decorator. Reraising any exception (except `CancelledError` and |
| 119 |
`NotImplementedError`) with universal exception |
| 120 |
:py:class:`aioftp.PathIOError` |
| 121 |
""" |
| 122 |
|
| 123 |
@functools.wraps(coro) |
| 124 |
async def wrapper( |
| 125 |
*args: UniversalExceptionParamSpec.args, |
| 126 |
**kwargs: UniversalExceptionParamSpec.kwargs, |
| 127 |
) -> UniversalExceptionReturnType: |
| 128 |
try: |
| 129 |
return await coro(*args, **kwargs) |
| 130 |
except ( |
| 131 |
asyncio.CancelledError, |
| 132 |
NotImplementedError, |
| 133 |
StopAsyncIteration, |
| 134 |
): |
| 135 |
raise |
| 136 |
except Exception as exc: |
| 137 |
raise PathIOError(reason=sys.exc_info()) from exc |
| 138 |
|
| 139 |
return wrapper |
| 140 |
|
| 141 |
|
| 142 |
class _DirNodeProtocol(Protocol): |
| 143 |
type: Literal["dir"] |
| 144 |
name: str |
| 145 |
ctime: int |
| 146 |
mtime: int |
| 147 |
content: list["NodeProtocol"] |
| 148 |
|
| 149 |
|
| 150 |
class _FileNodeProtocol(Protocol): |
| 151 |
type: Literal["file"] |
| 152 |
name: str |
| 153 |
ctime: int |
| 154 |
mtime: int |
| 155 |
content: io.BytesIO |
| 156 |
|
| 157 |
|
| 158 |
NodeProtocol = _DirNodeProtocol | _FileNodeProtocol |
| 159 |
|
| 160 |
|
| 161 |
class PathIONursery(Generic[PathIOType]): |
| 162 |
def __init__(self, factory: type["PathIOType"]) -> None: |
| 163 |
self.factory = factory |
| 164 |
self.state: list[Node] | None = None |
| 165 |
|
| 166 |
def __call__( |
| 167 |
self, |
| 168 |
timeout: float | int | None = None, |
| 169 |
connection: Connection | None = None, |
| 170 |
state: list["Node"] | None = None, |
| 171 |
) -> PathIOType: |
| 172 |
instance = self.factory(timeout=timeout, connection=connection, state=self.state) |
| 173 |
if self.state is None: |
| 174 |
self.state = instance.state |
| 175 |
return instance |
| 176 |
|
| 177 |
|
| 178 |
DefendFileMethodsParamSpec = ParamSpec("DefendFileMethodsParamSpec") |
| 179 |
DefendFileMethodsReturnType = TypeVar("DefendFileMethodsReturnType") |
| 180 |
|
| 181 |
|
| 182 |
def defend_file_methods( |
| 183 |
coro: Callable[ |
| 184 |
DefendFileMethodsParamSpec, |
| 185 |
Awaitable[DefendFileMethodsReturnType], |
| 186 |
], |
| 187 |
) -> Callable[ |
| 188 |
DefendFileMethodsParamSpec, |
| 189 |
Awaitable[DefendFileMethodsReturnType], |
| 190 |
]: |
| 191 |
""" |
| 192 |
Decorator. Raises exception when file methods called with wrapped by |
| 193 |
:py:class:`aioftp.AsyncPathIOContext` file object. |
| 194 |
""" |
| 195 |
|
| 196 |
@functools.wraps(coro) |
| 197 |
async def wrapper( |
| 198 |
*args: DefendFileMethodsParamSpec.args, |
| 199 |
**kwargs: DefendFileMethodsParamSpec.kwargs, |
| 200 |
) -> DefendFileMethodsReturnType: |
| 201 |
file = args[1] |
| 202 |
|
| 203 |
if isinstance(file, AsyncPathIOContext): |
| 204 |
raise ValueError( |
| 205 |
"Native path io file methods can not be used with wrapped file object", |
| 206 |
) |
| 207 |
return await coro(*args, **kwargs) |
| 208 |
|
| 209 |
return wrapper |
| 210 |
|
| 211 |
|
| 212 |
class PathlibOpenKwargs(TypedDict, total=False): |
| 213 |
mode: "OpenBinaryMode" |
| 214 |
buffering: int |
| 215 |
encoding: str | None |
| 216 |
errors: str | None |
| 217 |
newline: str | None |
| 218 |
|
| 219 |
|
| 220 |
PathType = TypeVar("PathType", bound=PurePath) |
| 221 |
|
| 222 |
|
| 223 |
class AbstractPathIO(Generic[PathType], abc.ABC): |
| 224 |
""" |
| 225 |
Abstract class for path io operations. |
| 226 |
|
| 227 |
:param timeout: timeout used by `with_timeout` decorator |
| 228 |
:type timeout: :py:class:`float`, :py:class:`int` or `None` |
| 229 |
|
| 230 |
:param connection: server connection that is accessing this PathIO |
| 231 |
:type connection: :py:class:`aioftp.Connection` |
| 232 |
|
| 233 |
:param state: shared pathio state per server |
| 234 |
""" |
| 235 |
|
| 236 |
def __init__( |
| 237 |
self, |
| 238 |
timeout: float | int | None = None, |
| 239 |
connection: Connection | None = None, |
| 240 |
state: list["Node"] | None = None, |
| 241 |
) -> None: |
| 242 |
self.timeout = timeout |
| 243 |
self.connection = connection |
| 244 |
|
| 245 |
@property |
| 246 |
def state(self) -> list["Node"] | None: |
| 247 |
""" |
| 248 |
Shared pathio state per server |
| 249 |
""" |
| 250 |
|
| 251 |
@universal_exception |
| 252 |
@abc.abstractmethod |
| 253 |
async def exists(self, path: PathType) -> bool: |
| 254 |
""" |
| 255 |
:py:func:`asyncio.coroutine` |
| 256 |
|
| 257 |
Check if path exists |
| 258 |
|
| 259 |
:param path: path to check |
| 260 |
:type path: :py:class:`pathlib.Path` |
| 261 |
|
| 262 |
:rtype: :py:class:`bool` |
| 263 |
""" |
| 264 |
|
| 265 |
@universal_exception |
| 266 |
@abc.abstractmethod |
| 267 |
async def is_dir(self, path: PathType) -> bool: |
| 268 |
""" |
| 269 |
:py:func:`asyncio.coroutine` |
| 270 |
|
| 271 |
Check if path is directory |
| 272 |
|
| 273 |
:param path: path to check |
| 274 |
:type path: :py:class:`pathlib.Path` |
| 275 |
|
| 276 |
:rtype: :py:class:`bool` |
| 277 |
""" |
| 278 |
|
| 279 |
@universal_exception |
| 280 |
@abc.abstractmethod |
| 281 |
async def is_file(self, path: PathType) -> bool: |
| 282 |
""" |
| 283 |
:py:func:`asyncio.coroutine` |
| 284 |
|
| 285 |
Check if path is file |
| 286 |
|
| 287 |
:param path: path to check |
| 288 |
:type path: :py:class:`pathlib.Path` |
| 289 |
|
| 290 |
:rtype: :py:class:`bool` |
| 291 |
""" |
| 292 |
|
| 293 |
@universal_exception |
| 294 |
@abc.abstractmethod |
| 295 |
async def mkdir(self, path: PathType, *, parents: bool = False, exist_ok: bool = False) -> None: |
| 296 |
""" |
| 297 |
:py:func:`asyncio.coroutine` |
| 298 |
|
| 299 |
Make directory |
| 300 |
|
| 301 |
:param path: path to create |
| 302 |
:type path: :py:class:`pathlib.Path` |
| 303 |
|
| 304 |
:param parents: create parents is does not exists |
| 305 |
:type parents: :py:class:`bool` |
| 306 |
|
| 307 |
:param exist_ok: do not raise exception if directory already exists |
| 308 |
:type exist_ok: :py:class:`bool` |
| 309 |
""" |
| 310 |
|
| 311 |
@universal_exception |
| 312 |
@abc.abstractmethod |
| 313 |
async def rmdir(self, path: PathType) -> None: |
| 314 |
""" |
| 315 |
:py:func:`asyncio.coroutine` |
| 316 |
|
| 317 |
Remove directory |
| 318 |
|
| 319 |
:param path: path to remove |
| 320 |
:type path: :py:class:`pathlib.Path` |
| 321 |
""" |
| 322 |
|
| 323 |
@universal_exception |
| 324 |
@abc.abstractmethod |
| 325 |
async def unlink(self, path: PathType) -> None: |
| 326 |
""" |
| 327 |
:py:func:`asyncio.coroutine` |
| 328 |
|
| 329 |
Remove file |
| 330 |
|
| 331 |
:param path: path to remove |
| 332 |
:type path: :py:class:`pathlib.Path` |
| 333 |
""" |
| 334 |
|
| 335 |
@abc.abstractmethod |
| 336 |
def list(self, path: PathType) -> AsyncIterable[PathType]: |
| 337 |
""" |
| 338 |
Create instance of subclass of :py:class:`aioftp.AbstractAsyncLister`. |
| 339 |
You should subclass and implement `__anext__` method |
| 340 |
for :py:class:`aioftp.AbstractAsyncLister` and return new instance. |
| 341 |
|
| 342 |
:param path: path to list |
| 343 |
:type path: :py:class:`pathlib.Path` |
| 344 |
|
| 345 |
:rtype: :py:class:`aioftp.AbstractAsyncLister` |
| 346 |
|
| 347 |
Usage: |
| 348 |
:: |
| 349 |
|
| 350 |
>>> async for p in pathio.list(path): |
| 351 |
... # do |
| 352 |
|
| 353 |
or borring instance of :py:class:`list`: |
| 354 |
:: |
| 355 |
|
| 356 |
>>> paths = await pathio.list(path) |
| 357 |
>>> paths |
| 358 |
[path, path, path, ...] |
| 359 |
|
| 360 |
""" |
| 361 |
|
| 362 |
@universal_exception |
| 363 |
@abc.abstractmethod |
| 364 |
async def stat(self, path: PathType) -> stat_result: |
| 365 |
""" |
| 366 |
:py:func:`asyncio.coroutine` |
| 367 |
|
| 368 |
Get path stats |
| 369 |
|
| 370 |
:param path: path, which stats need |
| 371 |
:type path: :py:class:`pathlib.Path` |
| 372 |
|
| 373 |
:return: path stats. For proper work you need only this stats: |
| 374 |
st_size, st_mtime, st_ctime, st_nlink, st_mode |
| 375 |
:rtype: same as :py:class:`os.stat_result` |
| 376 |
""" |
| 377 |
|
| 378 |
@universal_exception |
| 379 |
@abc.abstractmethod |
| 380 |
async def _open(self, path: PathType, mode: str) -> io.BytesIO: |
| 381 |
""" |
| 382 |
:py:func:`asyncio.coroutine` |
| 383 |
|
| 384 |
Open file. You should implement "mode" argument, which can be: |
| 385 |
"rb", "wb", "ab" (read, write, append. all binary). Return type depends |
| 386 |
on implementation, anyway the only place you need this file-object |
| 387 |
is in your implementation of read, write and close |
| 388 |
|
| 389 |
:param path: path to create |
| 390 |
:type path: :py:class:`pathlib.Path` |
| 391 |
|
| 392 |
:param mode: specifies the mode in which the file is opened ("rb", |
| 393 |
"wb", "ab", "r+b" (read, write, append, read/write, all binary)) |
| 394 |
:type mode: :py:class:`str` |
| 395 |
|
| 396 |
:return: file-object |
| 397 |
""" |
| 398 |
|
| 399 |
def open(self, *args: Unpack[tuple[PathType]], **kwargs: Unpack[_OpenKwargs]) -> AsyncPathIOContext: |
| 400 |
""" |
| 401 |
Create instance of :py:class:`aioftp.pathio.AsyncPathIOContext`, |
| 402 |
parameters passed to :py:meth:`aioftp.AbstractPathIO._open` |
| 403 |
|
| 404 |
:rtype: :py:class:`aioftp.pathio.AsyncPathIOContext` |
| 405 |
""" |
| 406 |
return AsyncPathIOContext(self, args, kwargs) |
| 407 |
|
| 408 |
@universal_exception |
| 409 |
@defend_file_methods |
| 410 |
@abc.abstractmethod |
| 411 |
async def seek(self, file: io.BytesIO, offset: int, whence: int = io.SEEK_SET) -> int: |
| 412 |
""" |
| 413 |
:py:func:`asyncio.coroutine` |
| 414 |
|
| 415 |
Change the stream position to the given byte `offset`. Same behaviour |
| 416 |
as :py:meth:`io.IOBase.seek` |
| 417 |
|
| 418 |
:param file: file-object from :py:class:`aioftp.AbstractPathIO.open` |
| 419 |
|
| 420 |
:param offset: relative byte offset |
| 421 |
:type offset: :py:class:`int` |
| 422 |
|
| 423 |
:param whence: base position for offset |
| 424 |
:type whence: :py:class:`int` |
| 425 |
""" |
| 426 |
|
| 427 |
@universal_exception |
| 428 |
@defend_file_methods |
| 429 |
@abc.abstractmethod |
| 430 |
async def write(self, file: io.BytesIO, data: bytes) -> int: |
| 431 |
""" |
| 432 |
:py:func:`asyncio.coroutine` |
| 433 |
|
| 434 |
Write some data to file |
| 435 |
|
| 436 |
:param file: file-object from :py:class:`aioftp.AbstractPathIO.open` |
| 437 |
|
| 438 |
:param data: data to write |
| 439 |
:type data: :py:class:`bytes` |
| 440 |
""" |
| 441 |
|
| 442 |
@universal_exception |
| 443 |
@defend_file_methods |
| 444 |
@abc.abstractmethod |
| 445 |
async def read(self, file: io.BytesIO, block_size: int) -> bytes: |
| 446 |
""" |
| 447 |
:py:func:`asyncio.coroutine` |
| 448 |
|
| 449 |
Read some data from file |
| 450 |
|
| 451 |
:param file: file-object from :py:class:`aioftp.AbstractPathIO.open` |
| 452 |
|
| 453 |
:param block_size: bytes count to read |
| 454 |
:type block_size: :py:class:`int` |
| 455 |
|
| 456 |
:rtype: :py:class:`bytes` |
| 457 |
""" |
| 458 |
|
| 459 |
@universal_exception |
| 460 |
@defend_file_methods |
| 461 |
@abc.abstractmethod |
| 462 |
async def close(self, file: io.BytesIO) -> None: |
| 463 |
""" |
| 464 |
:py:func:`asyncio.coroutine` |
| 465 |
|
| 466 |
Close file |
| 467 |
|
| 468 |
:param file: file-object from :py:class:`aioftp.AbstractPathIO.open` |
| 469 |
""" |
| 470 |
|
| 471 |
@universal_exception |
| 472 |
@abc.abstractmethod |
| 473 |
async def rename(self, source: PathType, destination: PathType) -> PathType: |
| 474 |
""" |
| 475 |
:py:func:`asyncio.coroutine` |
| 476 |
|
| 477 |
Rename path |
| 478 |
|
| 479 |
:param source: rename from |
| 480 |
:type source: :py:class:`pathlib.Path` |
| 481 |
|
| 482 |
:param destination: rename to |
| 483 |
:type destination: :py:class:`pathlib.Path` |
| 484 |
""" |
| 485 |
|
| 486 |
|
| 487 |
class PathIO(AbstractPathIO[Path]): |
| 488 |
""" |
| 489 |
Blocking path io. Directly based on :py:class:`pathlib.Path` methods. |
| 490 |
""" |
| 491 |
|
| 492 |
@universal_exception |
| 493 |
async def exists(self, path: Path) -> bool: |
| 494 |
return path.exists() |
| 495 |
|
| 496 |
@universal_exception |
| 497 |
async def is_dir(self, path: Path) -> bool: |
| 498 |
return path.is_dir() |
| 499 |
|
| 500 |
@universal_exception |
| 501 |
async def is_file(self, path: Path) -> bool: |
| 502 |
return path.is_file() |
| 503 |
|
| 504 |
@universal_exception |
| 505 |
async def mkdir(self, path: Path, *, parents: bool = False, exist_ok: bool = False) -> None: |
| 506 |
return path.mkdir(parents=parents, exist_ok=exist_ok) |
| 507 |
|
| 508 |
@universal_exception |
| 509 |
async def rmdir(self, path: Path) -> None: |
| 510 |
return path.rmdir() |
| 511 |
|
| 512 |
@universal_exception |
| 513 |
async def unlink(self, path: Path) -> None: |
| 514 |
return path.unlink() |
| 515 |
|
| 516 |
def list(self, path: Path) -> AsyncIterable[Path]: |
| 517 |
class Lister(AbstractAsyncLister[Path]): |
| 518 |
iter: Iterator[Path] | None = None |
| 519 |
|
| 520 |
@universal_exception |
| 521 |
async def __anext__(self) -> Path: |
| 522 |
if self.iter is None: |
| 523 |
self.iter = path.glob("*") |
| 524 |
try: |
| 525 |
return next(self.iter) |
| 526 |
except StopIteration: |
| 527 |
raise StopAsyncIteration |
| 528 |
|
| 529 |
return Lister(timeout=self.timeout) |
| 530 |
|
| 531 |
@universal_exception |
| 532 |
async def stat(self, path: Path) -> stat_result: |
| 533 |
return path.stat() |
| 534 |
|
| 535 |
@universal_exception |
| 536 |
async def _open( |
| 537 |
self, |
| 538 |
path: Path, |
| 539 |
mode: "OpenBinaryMode" = "rb", |
| 540 |
buffering: int = -1, |
| 541 |
encoding: str | None = None, |
| 542 |
errors: str | None = None, |
| 543 |
newline: str | None = None, |
| 544 |
) -> io.BytesIO: |
| 545 |
return path.open( |
| 546 |
mode=mode, |
| 547 |
buffering=buffering, |
| 548 |
encoding=encoding, |
| 549 |
errors=errors, |
| 550 |
newline=newline, |
| 551 |
) |
| 552 |
|
| 553 |
@universal_exception |
| 554 |
@defend_file_methods |
| 555 |
async def seek( |
| 556 |
self, |
| 557 |
file: io.BytesIO, |
| 558 |
offset: int, |
| 559 |
whence: int = io.SEEK_SET, |
| 560 |
) -> int: |
| 561 |
return file.seek(offset, whence) |
| 562 |
|
| 563 |
@universal_exception |
| 564 |
@defend_file_methods |
| 565 |
async def write(self, file: io.BytesIO, s: "ReadableBuffer") -> int: |
| 566 |
return file.write(s) |
| 567 |
|
| 568 |
@universal_exception |
| 569 |
@defend_file_methods |
| 570 |
async def read(self, file: io.BytesIO, n: int = -1) -> bytes: |
| 571 |
return file.read(n) |
| 572 |
|
| 573 |
@universal_exception |
| 574 |
@defend_file_methods |
| 575 |
async def close(self, file: io.BytesIO) -> None: |
| 576 |
return file.close() |
| 577 |
|
| 578 |
@universal_exception |
| 579 |
async def rename(self, source: Path, destination: Path) -> Path: |
| 580 |
return source.rename(destination) |
| 581 |
|
| 582 |
|
| 583 |
class HasExecutor(Protocol): |
| 584 |
executor: Executor | None |
| 585 |
|
| 586 |
|
| 587 |
_BlockingIOType = TypeVar("_BlockingIOType", bound=HasExecutor) |
| 588 |
_BlockingIOParamSpec = ParamSpec("_BlockingIOParamSpec") |
| 589 |
_BlockingIOReturnType = TypeVar("_BlockingIOReturnType") |
| 590 |
|
| 591 |
|
| 592 |
def _blocking_io( |
| 593 |
f: Callable[Concatenate[_BlockingIOType, _BlockingIOParamSpec], _BlockingIOReturnType], |
| 594 |
) -> Callable[Concatenate[_BlockingIOType, _BlockingIOParamSpec], Awaitable[_BlockingIOReturnType]]: |
| 595 |
@functools.wraps(f) |
| 596 |
async def wrapper( |
| 597 |
self: _BlockingIOType, |
| 598 |
*args: _BlockingIOParamSpec.args, |
| 599 |
**kwargs: _BlockingIOParamSpec.kwargs, |
| 600 |
) -> _BlockingIOReturnType: |
| 601 |
return await asyncio.get_running_loop().run_in_executor( |
| 602 |
self.executor, |
| 603 |
functools.partial(f, self, *args, **kwargs), |
| 604 |
) |
| 605 |
|
| 606 |
|
| 607 |
return wrapper |
| 608 |
|
| 609 |
|
| 610 |
class AsyncPathIO(AbstractPathIO[Path]): |
| 611 |
""" |
| 612 |
Non-blocking path io. Based on |
| 613 |
:py:meth:`asyncio.BaseEventLoop.run_in_executor` and |
| 614 |
:py:class:`pathlib.Path` methods. It's really slow, so it's better to avoid |
| 615 |
usage of this path io layer. |
| 616 |
|
| 617 |
:param executor: executor for running blocking tasks |
| 618 |
:type executor: :py:class:`concurrent.futures.Executor` |
| 619 |
""" |
| 620 |
|
| 621 |
def __init__( |
| 622 |
self, |
| 623 |
timeout: float | int | None = None, |
| 624 |
connection: Connection | None = None, |
| 625 |
state: list["Node"] | None = None, |
| 626 |
executor: Executor | None = None, |
| 627 |
) -> None: |
| 628 |
super().__init__(timeout, connection, state) |
| 629 |
self.executor = executor |
| 630 |
|
| 631 |
@universal_exception |
| 632 |
@with_timeout |
| 633 |
@_blocking_io |
| 634 |
def exists(self, path: Path) -> bool: |
| 635 |
return path.exists() |
| 636 |
|
| 637 |
@universal_exception |
| 638 |
@with_timeout |
| 639 |
@_blocking_io |
| 640 |
def is_dir(self, path: Path) -> bool: |
| 641 |
return path.is_dir() |
| 642 |
|
| 643 |
@universal_exception |
| 644 |
@with_timeout |
| 645 |
@_blocking_io |
| 646 |
def is_file(self, path: Path) -> bool: |
| 647 |
return path.is_file() |
| 648 |
|
| 649 |
@universal_exception |
| 650 |
@with_timeout |
| 651 |
@_blocking_io |
| 652 |
def mkdir(self, path: Path, *, parents: bool = False, exist_ok: bool = False) -> None: |
| 653 |
return path.mkdir(parents=parents, exist_ok=exist_ok) |
| 654 |
|
| 655 |
@universal_exception |
| 656 |
@with_timeout |
| 657 |
@_blocking_io |
| 658 |
def rmdir(self, path: Path) -> None: |
| 659 |
return path.rmdir() |
| 660 |
|
| 661 |
@universal_exception |
| 662 |
@with_timeout |
| 663 |
@_blocking_io |
| 664 |
def unlink(self, path: Path) -> None: |
| 665 |
return path.unlink() |
| 666 |
|
| 667 |
def list(self, path: Path) -> AsyncIterable[Path]: |
| 668 |
class Lister(AbstractAsyncLister[Path]): |
| 669 |
def __init__(self, timeout: float | int | None = None, executor: Executor | None = None) -> None: |
| 670 |
super().__init__(timeout=timeout) |
| 671 |
self.executor = executor |
| 672 |
self.iter: Iterator[Path] | None = None |
| 673 |
|
| 674 |
@universal_exception |
| 675 |
@with_timeout |
| 676 |
@_blocking_io |
| 677 |
def __anext__(self) -> Path: |
| 678 |
if self.iter is None: |
| 679 |
self.iter = path.glob("*") |
| 680 |
try: |
| 681 |
return next(self.iter) |
| 682 |
except StopIteration: |
| 683 |
raise StopAsyncIteration |
| 684 |
|
| 685 |
return Lister(timeout=self.timeout, executor=self.executor) |
| 686 |
|
| 687 |
@universal_exception |
| 688 |
@with_timeout |
| 689 |
@_blocking_io |
| 690 |
def stat(self, path: Path) -> stat_result: |
| 691 |
return path.stat() |
| 692 |
|
| 693 |
@universal_exception |
| 694 |
@with_timeout |
| 695 |
@_blocking_io |
| 696 |
def _open( |
| 697 |
self, |
| 698 |
path: Path, |
| 699 |
mode: "OpenBinaryMode" = "rb", |
| 700 |
buffering: int = -1, |
| 701 |
encoding: str | None = None, |
| 702 |
errors: str | None = None, |
| 703 |
newline: str | None = None, |
| 704 |
) -> io.BytesIO: |
| 705 |
return path.open( |
| 706 |
mode=mode, |
| 707 |
buffering=buffering, |
| 708 |
encoding=encoding, |
| 709 |
errors=errors, |
| 710 |
newline=newline, |
| 711 |
) |
| 712 |
|
| 713 |
@universal_exception |
| 714 |
@defend_file_methods |
| 715 |
@with_timeout |
| 716 |
@_blocking_io |
| 717 |
def seek( |
| 718 |
self, |
| 719 |
file: io.BytesIO, |
| 720 |
offset: int, |
| 721 |
whence: int = io.SEEK_SET, |
| 722 |
) -> int: |
| 723 |
return file.seek(offset, whence) |
| 724 |
|
| 725 |
@universal_exception |
| 726 |
@defend_file_methods |
| 727 |
@with_timeout |
| 728 |
@_blocking_io |
| 729 |
def write(self, file: io.BytesIO, s: "ReadableBuffer") -> int: |
| 730 |
return file.write(s) |
| 731 |
|
| 732 |
@universal_exception |
| 733 |
@defend_file_methods |
| 734 |
@with_timeout |
| 735 |
@_blocking_io |
| 736 |
def read(self, file: io.BytesIO, n: int = -1) -> bytes: |
| 737 |
return file.read(n) |
| 738 |
|
| 739 |
@universal_exception |
| 740 |
@defend_file_methods |
| 741 |
@with_timeout |
| 742 |
@_blocking_io |
| 743 |
def close(self, file: io.BytesIO) -> None: |
| 744 |
return file.close() |
| 745 |
|
| 746 |
@universal_exception |
| 747 |
@with_timeout |
| 748 |
@_blocking_io |
| 749 |
def rename(self, source: Path, destination: Path) -> Path: |
| 750 |
return source.rename(destination) |
| 751 |
|
| 752 |
|
| 753 |
class Node: |
| 754 |
@overload |
| 755 |
def __init__( |
| 756 |
self: _FileNodeProtocol, |
| 757 |
type: Literal["file"], |
| 758 |
name: str, |
| 759 |
ctime: int | None = None, |
| 760 |
mtime: int | None = None, |
| 761 |
*, |
| 762 |
content: io.BytesIO, |
| 763 |
) -> None: ... |
| 764 |
|
| 765 |
@overload |
| 766 |
def __init__( |
| 767 |
self: _DirNodeProtocol, |
| 768 |
type: Literal["dir"], |
| 769 |
name: str, |
| 770 |
ctime: int | None = None, |
| 771 |
mtime: int | None = None, |
| 772 |
*, |
| 773 |
content: list["Node"], |
| 774 |
) -> None: ... |
| 775 |
|
| 776 |
def __init__( |
| 777 |
self, |
| 778 |
type: Literal["dir", "file"], |
| 779 |
name: str, |
| 780 |
ctime: int | None = None, |
| 781 |
mtime: int | None = None, |
| 782 |
*, |
| 783 |
content: list["Node"] | io.BytesIO, |
| 784 |
) -> None: |
| 785 |
self.type = type |
| 786 |
self.name = name |
| 787 |
self.ctime = ctime or int(time.time()) |
| 788 |
self.mtime = mtime or int(time.time()) |
| 789 |
self.content = content |
| 790 |
|
| 791 |
def __repr__(self) -> str: |
| 792 |
return ( |
| 793 |
f"{self.__class__.__name__}(type={self.type!r}, " |
| 794 |
f"name={self.name!r}, ctime={self.ctime!r}, " |
| 795 |
f"mtime={self.mtime!r}, content={self.content!r})" |
| 796 |
) |
| 797 |
|
| 798 |
|
| 799 |
class MemoryPathIO(AbstractPathIO[PurePosixPath]): |
| 800 |
""" |
| 801 |
Non-blocking path io. Based on in-memory tree. It is just proof of concept |
| 802 |
and probably not so fast as it can be. |
| 803 |
""" |
| 804 |
|
| 805 |
class Stats(NamedTuple): |
| 806 |
st_size: int |
| 807 |
st_ctime: int |
| 808 |
st_mtime: int |
| 809 |
st_nlink: int |
| 810 |
st_mode: int |
| 811 |
|
| 812 |
def __init__( |
| 813 |
self, |
| 814 |
timeout: float | int | None = None, |
| 815 |
connection: Connection | None = None, |
| 816 |
state: list[Node] | None = None, |
| 817 |
cwd: str | PurePosixPath | None = None, |
| 818 |
) -> None: |
| 819 |
super().__init__(timeout=timeout, connection=connection) |
| 820 |
self.cwd = PurePosixPath(cwd or "/") |
| 821 |
if state is None: |
| 822 |
self.fs = [Node("dir", "/", content=[])] |
| 823 |
else: |
| 824 |
self.fs = state |
| 825 |
|
| 826 |
@property |
| 827 |
def state(self) -> list[Node]: |
| 828 |
return self.fs |
| 829 |
|
| 830 |
def __repr__(self) -> str: |
| 831 |
return repr(self.fs) |
| 832 |
|
| 833 |
def _absolute(self, path: PurePosixPath) -> PurePosixPath: |
| 834 |
if not path.is_absolute(): |
| 835 |
path = self.cwd / path |
| 836 |
return path |
| 837 |
|
| 838 |
def get_node(self, path: PurePosixPath) -> Node | None: |
| 839 |
nodes: list[Node] | io.BytesIO = self.fs |
| 840 |
node = None |
| 841 |
path = self._absolute(path) |
| 842 |
for part in path.parts: |
| 843 |
if not isinstance(nodes, list): |
| 844 |
return None |
| 845 |
for node in nodes: |
| 846 |
if node.name == part: |
| 847 |
nodes = node.content |
| 848 |
break |
| 849 |
else: |
| 850 |
return None |
| 851 |
return node |
| 852 |
|
| 853 |
@universal_exception |
| 854 |
async def exists(self, path: PurePosixPath) -> bool: |
| 855 |
return self.get_node(path) is not None |
| 856 |
|
| 857 |
@universal_exception |
| 858 |
async def is_dir(self, path: PurePosixPath) -> bool: |
| 859 |
node = self.get_node(path) |
| 860 |
return not (node is None or node.type != "dir") |
| 861 |
|
| 862 |
@universal_exception |
| 863 |
async def is_file(self, path: PurePosixPath) -> bool: |
| 864 |
node = self.get_node(path) |
| 865 |
return not (node is None or node.type != "file") |
| 866 |
|
| 867 |
@universal_exception |
| 868 |
async def mkdir(self, path: PurePosixPath, *, parents: bool = False, exist_ok: bool = False) -> None: |
| 869 |
path_ = self._absolute(path) |
| 870 |
node = self.get_node(path_) |
| 871 |
if node: |
| 872 |
if node.type != "dir" or not exist_ok: |
| 873 |
raise FileExistsError |
| 874 |
elif not parents: |
| 875 |
parent = self.get_node(path_.parent) |
| 876 |
if parent is None: |
| 877 |
raise FileNotFoundError |
| 878 |
if isinstance(parent.content, io.BytesIO): |
| 879 |
raise NotADirectoryError |
| 880 |
node = Node("dir", path_.name, content=[]) |
| 881 |
parent.content.append(node) |
| 882 |
else: |
| 883 |
nodes: list[Node] | io.BytesIO = self.fs |
| 884 |
for part in path_.parts: |
| 885 |
if isinstance(nodes, list): |
| 886 |
for node in nodes: |
| 887 |
if node.name == part: |
| 888 |
nodes = node.content |
| 889 |
break |
| 890 |
else: |
| 891 |
node = Node("dir", part, content=[]) |
| 892 |
nodes.append(node) |
| 893 |
nodes = node.content |
| 894 |
else: |
| 895 |
raise NotADirectoryError |
| 896 |
|
| 897 |
@universal_exception |
| 898 |
async def rmdir(self, path: PurePosixPath) -> None: |
| 899 |
node = self.get_node(path) |
| 900 |
if node is None: |
| 901 |
raise FileNotFoundError |
| 902 |
if node.type != "dir": |
| 903 |
raise NotADirectoryError |
| 904 |
if node.content: |
| 905 |
raise OSError("Directory not empty") |
| 906 |
|
| 907 |
parent = self.get_node(path.parent) |
| 908 |
if parent is None: |
| 909 |
raise FileNotFoundError |
| 910 |
if not isinstance(parent.content, list): |
| 911 |
raise NotADirectoryError |
| 912 |
for i, node in enumerate(parent.content): |
| 913 |
if node.name == path.name: |
| 914 |
break |
| 915 |
parent.content.pop(i) |
| 916 |
|
| 917 |
@universal_exception |
| 918 |
async def unlink(self, path: PurePosixPath) -> None: |
| 919 |
node = self.get_node(path) |
| 920 |
if node is None: |
| 921 |
raise FileNotFoundError |
| 922 |
if node.type != "file": |
| 923 |
raise IsADirectoryError |
| 924 |
|
| 925 |
parent = self.get_node(path.parent) |
| 926 |
if parent is None: |
| 927 |
raise FileNotFoundError |
| 928 |
if not isinstance(parent.content, list): |
| 929 |
raise NotADirectoryError |
| 930 |
for i, node in enumerate(parent.content): |
| 931 |
if node.name == path.name: |
| 932 |
break |
| 933 |
parent.content.pop(i) |
| 934 |
|
| 935 |
def list(self, path: PurePosixPath) -> AsyncIterable[PurePosixPath]: |
| 936 |
class Lister(AbstractAsyncLister[PurePosixPath]): |
| 937 |
iter: Iterator[PurePosixPath] | None = None |
| 938 |
|
| 939 |
@universal_exception |
| 940 |
async def __anext__(cls) -> PurePosixPath: |
| 941 |
if cls.iter is None: |
| 942 |
node = self.get_node(path) |
| 943 |
if node is None or node.type != "dir": |
| 944 |
cls.iter = iter(()) |
| 945 |
else: |
| 946 |
names = map(operator.attrgetter("name"), node.content) |
| 947 |
paths = map(lambda name: path / name, names) |
| 948 |
cls.iter = iter(paths) |
| 949 |
try: |
| 950 |
return next(cls.iter) |
| 951 |
except StopIteration: |
| 952 |
raise StopAsyncIteration |
| 953 |
|
| 954 |
return Lister(timeout=self.timeout) |
| 955 |
|
| 956 |
@universal_exception |
| 957 |
async def stat(self, path: PurePosixPath) -> "MemoryPathIO.Stats": |
| 958 |
node = self.get_node(path) |
| 959 |
if node is None: |
| 960 |
raise FileNotFoundError |
| 961 |
|
| 962 |
if isinstance(node.content, io.BytesIO): |
| 963 |
size = len(node.content.getbuffer()) |
| 964 |
mode = stat.S_IFREG | 0o666 |
| 965 |
else: |
| 966 |
size = 0 |
| 967 |
mode = stat.S_IFDIR | 0o777 |
| 968 |
return MemoryPathIO.Stats( |
| 969 |
size, |
| 970 |
node.ctime, |
| 971 |
node.mtime, |
| 972 |
1, |
| 973 |
mode, |
| 974 |
) |
| 975 |
|
| 976 |
@universal_exception |
| 977 |
async def _open( |
| 978 |
self, |
| 979 |
path: PurePosixPath, |
| 980 |
mode: "OpenBinaryMode" = "rb", |
| 981 |
) -> io.BytesIO: |
| 982 |
if mode == "rb": |
| 983 |
node = self.get_node(path) |
| 984 |
if node is None: |
| 985 |
raise FileNotFoundError |
| 986 |
if isinstance(node.content, list): |
| 987 |
raise IsADirectoryError |
| 988 |
file_like: io.BytesIO = node.content |
| 989 |
file_like.seek(0, io.SEEK_SET) |
| 990 |
elif mode in ("wb", "ab", "r+b"): |
| 991 |
node = self.get_node(path) |
| 992 |
if node is None: |
| 993 |
parent = self.get_node(path.parent) |
| 994 |
if parent is None or not isinstance(parent.content, list): |
| 995 |
raise FileNotFoundError |
| 996 |
content = io.BytesIO() |
| 997 |
new_node = Node("file", path.name, content=content) |
| 998 |
parent.content.append(new_node) |
| 999 |
file_like = content |
| 1000 |
elif node.type != "file": |
| 1001 |
raise IsADirectoryError |
| 1002 |
else: |
| 1003 |
if isinstance(node.content, list): |
| 1004 |
raise IsADirectoryError |
| 1005 |
if mode == "wb": |
| 1006 |
file_like = node.content = io.BytesIO() |
| 1007 |
elif mode == "ab": |
| 1008 |
file_like = node.content |
| 1009 |
file_like.seek(0, io.SEEK_END) |
| 1010 |
elif mode == "r+b": |
| 1011 |
file_like = node.content |
| 1012 |
file_like.seek(0, io.SEEK_SET) |
| 1013 |
else: |
| 1014 |
raise ValueError(f"invalid mode: {mode}") |
| 1015 |
return file_like |
| 1016 |
|
| 1017 |
@universal_exception |
| 1018 |
@defend_file_methods |
| 1019 |
async def seek(self, file: io.BytesIO, offset: int, whence: int = io.SEEK_SET) -> int: |
| 1020 |
return file.seek(offset, whence) |
| 1021 |
|
| 1022 |
@universal_exception |
| 1023 |
@defend_file_methods |
| 1024 |
async def write(self, file: io.BytesIO, buffer: "ReadableBuffer") -> int: |
| 1025 |
x = file.write(buffer) |
| 1026 |
file.mtime = int(time.time()) |
| 1027 |
return x |
| 1028 |
|
| 1029 |
@universal_exception |
| 1030 |
@defend_file_methods |
| 1031 |
async def read(self, file: io.BytesIO, size: int | None = -1) -> bytes: |
| 1032 |
return file.read(size) |
| 1033 |
|
| 1034 |
@universal_exception |
| 1035 |
@defend_file_methods |
| 1036 |
async def close(self, file: io.BytesIO) -> None: |
| 1037 |
pass |
| 1038 |
|
| 1039 |
@universal_exception |
| 1040 |
async def rename(self, source: PurePosixPath, destination: PurePosixPath) -> PurePosixPath: |
| 1041 |
if source != destination: |
| 1042 |
sparent = self.get_node(source.parent) |
| 1043 |
dparent = self.get_node(destination.parent) |
| 1044 |
snode = self.get_node(source) |
| 1045 |
if snode is None: |
| 1046 |
raise FileNotFoundError |
| 1047 |
if dparent is None: |
| 1048 |
raise FileNotFoundError |
| 1049 |
if isinstance(dparent.content, io.BytesIO): |
| 1050 |
raise NotADirectoryError |
| 1051 |
if sparent is None: |
| 1052 |
raise FileNotFoundError |
| 1053 |
if isinstance(sparent.content, io.BytesIO): |
| 1054 |
raise NotADirectoryError |
| 1055 |
for i, node in enumerate(sparent.content): |
| 1056 |
if node.name == source.name: |
| 1057 |
sparent.content.pop(i) |
| 1058 |
snode.name = destination.name |
| 1059 |
for i, node in enumerate(dparent.content): |
| 1060 |
if node.name == destination.name: |
| 1061 |
dparent.content[i] = snode |
| 1062 |
break |
| 1063 |
else: |
| 1064 |
dparent.content.append(snode) |
| 1065 |
return destination |