v0.166.0
  1import os
  2from functools import cached_property
  3from io import UnsupportedOperation
  4from types import TracebackType
  5from typing import TYPE_CHECKING, Self
  6
  7from plain.internal.files.utils import FileProxyMixin
  8
  9if TYPE_CHECKING:
 10    from collections.abc import Iterator
 11    from typing import IO, Any
 12
 13
 14class File(FileProxyMixin):
 15    DEFAULT_CHUNK_SIZE = 64 * 2**10
 16
 17    def __init__(self, file: IO[Any], name: str | None = None) -> None:
 18        self.file = file
 19        if name is None:
 20            name = getattr(file, "name", None)
 21        self.name = name
 22        if hasattr(file, "mode"):
 23            self.mode = file.mode
 24
 25    def __str__(self) -> str:
 26        return self.name or ""
 27
 28    def __repr__(self) -> str:
 29        return "<{}: {}>".format(self.__class__.__name__, self or "None")
 30
 31    def __bool__(self) -> bool:
 32        return bool(self.name)
 33
 34    def __len__(self) -> int:
 35        return self.size
 36
 37    @cached_property
 38    def size(self) -> int:
 39        if hasattr(self.file, "size"):
 40            return self.file.size  # ty: ignore[invalid-return-type]
 41        if hasattr(self.file, "name"):
 42            try:
 43                return os.path.getsize(self.file.name)
 44            except OSError, TypeError:
 45                pass
 46        if hasattr(self.file, "tell") and hasattr(self.file, "seek"):
 47            pos = self.file.tell()
 48            self.file.seek(0, os.SEEK_END)
 49            size = self.file.tell()
 50            self.file.seek(pos)
 51            return size
 52        raise AttributeError("Unable to determine the file's size.")
 53
 54    def chunks(self, chunk_size: int | None = None) -> Iterator[bytes]:
 55        """
 56        Read the file and yield chunks of ``chunk_size`` bytes (defaults to
 57        ``File.DEFAULT_CHUNK_SIZE``).
 58        """
 59        chunk_size = chunk_size or self.DEFAULT_CHUNK_SIZE
 60        try:
 61            self.seek(0)
 62        except AttributeError, UnsupportedOperation:
 63            pass
 64
 65        while True:
 66            data = self.read(chunk_size)
 67            if not data:
 68                break
 69            yield data
 70
 71    def multiple_chunks(self, chunk_size: int | None = None) -> bool:
 72        """
 73        Return ``True`` if you can expect multiple chunks.
 74
 75        NB: If a particular file representation is in memory, subclasses should
 76        always return ``False`` -- there's no good reason to read from memory in
 77        chunks.
 78        """
 79        return self.size > (chunk_size or self.DEFAULT_CHUNK_SIZE)
 80
 81    def __iter__(self) -> Iterator[bytes | str]:
 82        # Iterate over this file-like object by newlines
 83        buffer_ = None
 84        for chunk in self.chunks():
 85            for line in chunk.splitlines(True):
 86                if buffer_:
 87                    if endswith_cr(buffer_) and not equals_lf(line):
 88                        # Line split after a \r newline; yield buffer_.
 89                        yield buffer_
 90                        # Continue with line.
 91                    else:
 92                        # Line either split without a newline (line
 93                        # continues after buffer_) or with \r\n
 94                        # newline (line == b'\n').
 95                        line = buffer_ + line
 96                    # buffer_ handled, clear it.
 97                    buffer_ = None
 98
 99                # If this is the end of a \n or \r\n line, yield.
100                if endswith_lf(line):
101                    yield line
102                else:
103                    buffer_ = line
104
105        if buffer_ is not None:
106            yield buffer_
107
108    def __enter__(self) -> Self:
109        return self
110
111    def __exit__(
112        self,
113        exc_type: type[BaseException] | None,
114        exc_value: BaseException | None,
115        tb: TracebackType | None,
116    ) -> None:
117        self.close()
118
119    def open(self, mode: str | None = None) -> File:
120        if not self.closed:
121            self.seek(0)
122        elif self.name and os.path.exists(self.name):
123            self.file = open(self.name, mode or self.mode)  # noqa: SIM115 — File owns and closes it
124        else:
125            raise ValueError("The file cannot be reopened.")
126        return self
127
128    def close(self) -> None:
129        self.file.close()
130
131
132def endswith_cr(line: str | bytes) -> bool:
133    """Return True if line (a text or bytestring) ends with '\r'."""
134    if isinstance(line, str):
135        return line.endswith("\r")
136    return line.endswith(b"\r")
137
138
139def endswith_lf(line: str | bytes) -> bool:
140    """Return True if line (a text or bytestring) ends with '\n'."""
141    if isinstance(line, str):
142        return line.endswith("\n")
143    return line.endswith(b"\n")
144
145
146def equals_lf(line: str | bytes) -> bool:
147    """Return True if line (a text or bytestring) equals '\n'."""
148    return line == ("\n" if isinstance(line, str) else b"\n")