From caeb40141e70235531d13728eacc3bf35f04beaf Mon Sep 17 00:00:00 2001 From: Ladislav Laska Date: Tue, 22 Sep 2026 14:56:26 +0200 Subject: [PATCH 1/3] Add pathlib-style path objects. Implements the pathlib ABCs from pathlib-abc under the LittleFS.root property. These allow pathlib-like filesystem traversal. - pathlib-abc requires Python 3.9+ and should be upstreamed in core python in a future release. It provides most of the Pathlib API. - on Python 3.8 this API is unavailable. When Python 3.8 support is dropped, conditional/lazy imports can be cleaned up. --- mypy.ini | 3 + setup.py | 4 + src/littlefs/__init__.py | 36 +++- src/littlefs/path.py | 424 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 466 insertions(+), 1 deletion(-) create mode 100644 src/littlefs/path.py diff --git a/mypy.ini b/mypy.ini index 32e726a..764e555 100644 --- a/mypy.ini +++ b/mypy.ini @@ -3,3 +3,6 @@ check_untyped_defs = True [mypy-pytest.*] ignore_missing_imports = True + +[mypy-pathlib_abc.*] +ignore_missing_imports = True diff --git a/setup.py b/setup.py index a7fb093..2fab76c 100644 --- a/setup.py +++ b/setup.py @@ -47,6 +47,10 @@ }, install_requires=[ "importlib-metadata>=4.4; python_version < '3.10'", + # Provides the pathlib ABCs backing littlefs.path / LittleFS.root. + # pathlib-abc itself requires Python 3.9+, so the pathlib-style API is + # unavailable on 3.8. + "pathlib-abc>=0.5.2; python_version >= '3.9'", ], classifiers=[ "Development Status :: 3 - Alpha", diff --git a/src/littlefs/__init__.py b/src/littlefs/__init__.py index f76ac2a..9f93738 100644 --- a/src/littlefs/__init__.py +++ b/src/littlefs/__init__.py @@ -33,6 +33,7 @@ "LFSStat", "LittleFS", "LittleFSError", + "LittleFSPath", "UserContext", "UserContextFile", "UserContextWinDisk", @@ -53,6 +54,17 @@ if TYPE_CHECKING: from .lfs import LFSStat + from .path import LittleFSPath + + +def __getattr__(name: str): + # ``littlefs.path`` needs the optional ``pathlib-abc`` dependency, so it is + # imported lazily: ``import littlefs`` must keep working without it. + if name == "LittleFSPath": + from .path import LittleFSPath + + return LittleFSPath + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") class LittleFS: @@ -104,6 +116,22 @@ def context(self) -> "UserContext": """User context of the file system""" return self.cfg.user_context + @property + def root(self) -> "LittleFSPath": + """The filesystem root (``/``) as a :class:`littlefs.path.LittleFSPath`. + + This is the entry point to the ``pathlib``-style API; every path derived + from it stays bound to this filesystem:: + + (fs.root / "logs").mkdir() + (fs.root / "logs" / "boot.txt").write_text("ready\\n") + + Requires Python 3.9 or later; see :mod:`littlefs.path` for the caveats. + """ + from .path import LittleFSPath + + return LittleFSPath("/", fs=self) + def format(self) -> int: """Format the underlying buffer""" if self.cfg.block_count == 0: @@ -144,7 +172,13 @@ def fs_gc(self): return lfs.fs_gc(self.fs) def open( - self, fname: str, mode="r", buffering: int = -1, encoding: str = None, errors: str = None, newline: str = None + self, + fname: str, + mode="r", + buffering: int = -1, + encoding: Optional[str] = None, + errors: Optional[str] = None, + newline: Optional[str] = None, ) -> IO: """Open a file. diff --git a/src/littlefs/path.py b/src/littlefs/path.py new file mode 100644 index 0000000..e9bfdce --- /dev/null +++ b/src/littlefs/path.py @@ -0,0 +1,424 @@ +"""``pathlib``-style access to a littlefs filesystem + +It can be navigated with the familiar :class:`pathlib.Path` API:: + + from littlefs import LittleFS + + fs = LittleFS(block_size=512, block_count=256) + (fs.root / "logs").mkdir() + (fs.root / "logs" / "boot.txt").write_text("ready\\n") + for path in fs.root.rglob("*.txt"): + print(path, path.read_text()) + +Every path derived from :attr:`LittleFS.root` stays bound to the same +filesystem handle, so all I/O is routed through it. + +.. note:: + To use this ``pathlib``-like API you need **Python 3.9 or later**. On 3.8 and + earlier, importing this module or accessing :attr:`LittleFS.root` raises + :exc:`ImportError`; the rest of littlefs-python is unaffected either way. + + Under the hood it uses `pathlib-abc + `_, which is pre-1.0 and still under + discussion for inclusion in CPython's :mod:`pathlib`. Support is therefore + **provisional** and may have to follow breaking changes in it. +""" + +import posixpath +from typing import IO, Iterator, List, Optional, Union + +try: + from pathlib_abc import JoinablePath, ReadablePath, WritablePath, vfspath +except ImportError as exc: # pragma: no cover - depends on the install environment + raise ImportError( + "littlefs.path requires the 'pathlib-abc' package, which is only " + "available on Python 3.9 and later. Install it with " + "`pip install pathlib-abc`." + ) from exc + +from littlefs import LittleFS + +from .errors import LittleFSError +from . import lfs + +__all__ = ["LittleFSPath", "LittleFSPathInfo"] + + +_ENOENT = int(LittleFSError.Error.LFS_ERR_NOENT) +_EEXIST = int(LittleFSError.Error.LFS_ERR_EXIST) +_ENOTDIR = int(LittleFSError.Error.LFS_ERR_NOTDIR) + +# Segment types accepted when building a path. +_StrPath = Union[str, "LittleFSPath"] + + +def _stat_or_none(fs: LittleFS, path: str) -> Optional[lfs.LFSStat]: + """``fs.stat(path)``, or ``None`` if the path does not exist + + A missing path raises either :class:`LittleFSError` with ``LFS_ERR_NOENT`` or + the builtin :class:`FileNotFoundError`, depending on the call; both mean the + same thing here. + """ + try: + return fs.stat(path) + except FileNotFoundError: + return None + except LittleFSError as exc: + if exc.code == _ENOENT: + return None + raise + + +def _segment_to_str(segment: _StrPath) -> str: + """Normalise a path segment to a string""" + if isinstance(segment, str): + return segment + if isinstance(segment, JoinablePath): + return vfspath(segment) + # os.PathLike is deliberately not accepted: a host filesystem path means + # nothing inside littlefs. TypeError is what lets ``__truediv__`` return + # NotImplemented. + raise TypeError(f"expected a str or LittleFSPath segment, not {type(segment).__name__}") + + +class LittleFSPathInfo: + """File type information for a :class:`LittleFSPath`. + + Satisfies the ``PathInfo`` protocol. One :meth:`LittleFS.stat` result is + fetched on first use and then **cached**, as the protocol permits, which is + what makes ``glob``/``walk`` cheap. + + The ``follow_symlinks`` arguments are accepted and ignored: littlefs has no + symbolic links. + """ + + __slots__ = ("_fs", "_path", "_stat", "_stat_cached") + + def __init__(self, fs: Optional[LittleFS], path: str, stat: Optional[lfs.LFSStat] = None) -> None: + self._fs = fs + self._path = path + self._stat = stat + # ``stat`` may be supplied by ``iterdir()``, which already learned the + # file type while listing the parent directory. + self._stat_cached = stat is not None + + def _lfs_stat(self) -> Optional[lfs.LFSStat]: + if not self._stat_cached: + if self._fs is None: + raise ValueError(f"{self._path!r} is not bound to a LittleFS handle") + self._stat = _stat_or_none(self._fs, self._path) + self._stat_cached = True + return self._stat + + def exists(self, *, follow_symlinks: bool = True) -> bool: + """Whether this path exists""" + return self._lfs_stat() is not None + + def is_dir(self, *, follow_symlinks: bool = True) -> bool: + """Whether this path is a directory""" + stat = self._lfs_stat() + return stat is not None and stat.type == lfs.LFSStat.TYPE_DIR + + def is_file(self, *, follow_symlinks: bool = True) -> bool: + """Whether this path is a regular file""" + stat = self._lfs_stat() + return stat is not None and stat.type == lfs.LFSStat.TYPE_REG + + def is_symlink(self) -> bool: + """Always ``False``: littlefs has no symbolic links""" + return False + + def _file_id(self) -> tuple: + """Identify the file this path names, for ``copy()``'s same-file check + + ``pathlib_abc``'s copy helpers fall back to comparing paths without this, + which is not enough here: ``"notes.txt"`` and ``"/notes.txt"`` are one + file but two unequal paths. There are no inode numbers, so the + normalized absolute path stands in, with the handle included so copies + between filesystems stay allowed. + """ + return (id(self._fs), posixpath.normpath(posixpath.join("/", self._path))) + + +class LittleFSPath(ReadablePath, WritablePath): + """A path inside a littlefs filesystem, bound to its :class:`LittleFS` handle. + + Instances are normally obtained from :attr:`LittleFS.root` and combined with + ``/``; the bound handle propagates to every derived path (``parent``, ``/``, + ``with_suffix``, ``glob`` results, ...) through :meth:`with_segments`. + + Pure path behaviour (``parts``, ``name``, ``stem``, ``suffix``, ``parent``, + ``relative_to``, ``full_match``, ...) and ``glob``/``rglob``/``walk``/ + ``copy`` come from the :mod:`pathlib` ABCs. Everything that touches the + filesystem delegates to the bound handle. + + littlefs resolves every path from the filesystem root, so a "relative" path + reaches the same file as its absolute equivalent. :attr:`info` caches its + lookup, while :meth:`exists`, :meth:`is_dir` and :meth:`is_file` always look + afresh. + """ + + __slots__ = ("_fs", "_path", "_info") + + # Annotations only; the values live in __slots__. + _fs: Optional[LittleFS] + _path: str + _info: Optional[LittleFSPathInfo] + + #: littlefs is always POSIX: ``/`` separator, no alternative separator. + parser = posixpath + + def __init__(self, *pathsegments: _StrPath, fs: Optional[LittleFS] = None) -> None: + if fs is None: + # Inherit the handle when built from another bound path. + fs = next((seg._fs for seg in pathsegments if isinstance(seg, LittleFSPath)), None) + if fs is not None and not isinstance(fs, LittleFS): + # Common slip: passing the low-level ``littlefs.lfs.LFSFilesystem`` + # struct (a ``LittleFS`` handle's ``.fs`` attribute) instead of the + # handle itself. Without this guard it fails much later, inside + # ``stat()``, with a confusing AttributeError. + raise TypeError( + f"expected a high-level littlefs.LittleFS handle, got " + f"{type(fs).__module__}.{type(fs).__qualname__}. If you have a " + f"LittleFS `fs`, pass `fs` itself, not `fs.fs`." + ) + self._fs = fs + parts = [_segment_to_str(seg) for seg in pathsegments] + # Plain posixpath joining, which importantly preserves a trailing + # separator: the ABC's globber relies on ``joinpath("")`` yielding + # ``"/dir/"`` so that it can concatenate the next pattern part onto it. + self._path = posixpath.join(*parts) if parts else "" + self._info = None + + # -- pure path surface ------------------------------------------------------ + def __vfspath__(self) -> str: + """The string representation of this path""" + return self._path + + def __str__(self) -> str: + return self._path + + def __repr__(self) -> str: + return f"{type(self).__name__}({self._path!r})" + + # NOTE: ``__fspath__`` is deliberately *not* implemented. ``pathlib_abc``'s + # ``vfsopen()`` tries the builtin ``open()`` first, so an os.PathLike path + # object would make ``read_text()``/``write_bytes()`` silently operate on the + # host filesystem instead of littlefs. + + # The ABCs omit these, but relative_to() and copy() depend on __eq__. + def __eq__(self, other: object) -> bool: + if not isinstance(other, LittleFSPath): + return NotImplemented + # The handle is part of the identity: the same string on two different + # filesystems is not the same file. + return self._path == other._path and self._fs is other._fs + + def __hash__(self) -> int: + return hash((self._path, id(self._fs))) + + def __lt__(self, other: object) -> bool: + if not isinstance(other, LittleFSPath): + return NotImplemented + return self._path < other._path + + def __le__(self, other: object) -> bool: + if not isinstance(other, LittleFSPath): + return NotImplemented + return self._path <= other._path + + def __gt__(self, other: object) -> bool: + if not isinstance(other, LittleFSPath): + return NotImplemented + return self._path > other._path + + def __ge__(self, other: object) -> bool: + if not isinstance(other, LittleFSPath): + return NotImplemented + return self._path >= other._path + + def with_segments(self, *pathsegments: _StrPath) -> "LittleFSPath": + """Construct a new path of the same type, bound to the same handle""" + return type(self)(*pathsegments, fs=self._fs) + + def as_posix(self) -> str: + """The string representation of this path, always POSIX style""" + return self._path + + def is_absolute(self) -> bool: + """Whether this path starts at the filesystem root""" + return self._path.startswith("/") + + @property + def fs(self) -> LittleFS: + """The bound :class:`LittleFS` handle""" + if self._fs is None: + raise ValueError(f"{self!r} is not bound to a LittleFS handle") + return self._fs + + # -- filesystem queries ----------------------------------------------------- + @property + def info(self) -> LittleFSPathInfo: + """A :class:`LittleFSPathInfo` for this path, created once and cached""" + if self._info is None: + self._info = LittleFSPathInfo(self._fs, self._path) + return self._info + + def stat(self) -> lfs.LFSStat: + """Return the :class:`littlefs.lfs.LFSStat` for this path + + Raises :class:`LittleFSError` if the path does not exist. + """ + return self.fs.stat(self._path) + + def exists(self) -> bool: + """Whether this path exists""" + return _stat_or_none(self.fs, self._path) is not None + + def is_dir(self) -> bool: + """Whether this path is a directory""" + stat = _stat_or_none(self.fs, self._path) + return stat is not None and stat.type == lfs.LFSStat.TYPE_DIR + + def is_file(self) -> bool: + """Whether this path is a regular file""" + stat = _stat_or_none(self.fs, self._path) + return stat is not None and stat.type == lfs.LFSStat.TYPE_REG + + def is_symlink(self) -> bool: + """Always ``False``: littlefs has no symbolic links""" + return False + + def iterdir(self) -> Iterator["LittleFSPath"]: + """Return an iterator over the children of this directory + + :exc:`NotADirectoryError` and :exc:`FileNotFoundError` are raised by this + call rather than while iterating the result. + """ + # ``scandir`` already reports each entry's type, so prime the children's + # info caches with it and save a stat() apiece. Materialised here so the + # directory handle is closed before anything is yielded: callers commonly + # mutate the tree while iterating. + try: + entries: List[lfs.LFSStat] = list(self.fs.scandir(self._path)) + except LittleFSError as exc: + # Translated to the builtins, as the rest of the high-level API + # does. LittleFSError is not an OSError, so glob()/walk() would + # otherwise never catch these. + if exc.code == _ENOTDIR: + raise NotADirectoryError(f"Not a directory: '{self._path}'") from exc + if exc.code == _ENOENT: + raise FileNotFoundError(f"No such file or directory: '{self._path}'") from exc + raise + return self._iter_entries(entries) + + def _iter_entries(self, entries: List[lfs.LFSStat]) -> Iterator["LittleFSPath"]: + for entry in entries: + child = self.with_segments(self._path, entry.name) + child._info = LittleFSPathInfo(self._fs, child._path, stat=entry) + yield child + + def rglob(self, pattern: str, *, recurse_symlinks: bool = True) -> Iterator["LittleFSPath"]: + """Recursive :meth:`glob`, equivalent to ``glob("**/" + pattern)``""" + return self.glob(f"**/{pattern}", recurse_symlinks=recurse_symlinks) + + def readlink(self) -> "LittleFSPath": + """Always raises: littlefs has no symbolic links""" + raise NotImplementedError("littlefs does not support symbolic links") + + # -- file I/O --------------------------------------------------------------- + def open( + self, + mode: str = "r", + buffering: int = -1, + encoding: Optional[str] = None, + errors: Optional[str] = None, + newline: Optional[str] = None, + ) -> IO: + """Open this file, like :meth:`LittleFS.open`""" + return self.fs.open(self._path, mode, buffering, encoding, errors, newline) + + def __open_reader__(self) -> IO: + """Open this file for binary reading""" + return self.fs.open(self._path, "rb") + + def __open_writer__(self, mode: str) -> IO: + """Open this file for binary writing in ``'a'``, ``'w'`` or ``'x'`` mode""" + return self.fs.open(self._path, mode + "b") + + def touch(self, exist_ok: bool = True) -> None: + """Create this file if it does not exist + + littlefs records no modification time, so unlike + :meth:`pathlib.Path.touch` this cannot refresh one: touching an existing + file is a no-op. + """ + try: + with self.fs.open(self._path, "xb"): + pass + except FileExistsError: + if not exist_ok: + raise + except LittleFSError as exc: + if exc.code != _EEXIST or not exist_ok: + raise + + # -- mutations -------------------------------------------------------------- + def mkdir(self, parents: bool = False, exist_ok: bool = False) -> None: + """Create this directory. + + With *parents*, any missing parent directories are created as well; with + *exist_ok*, an already existing directory is not an error. + """ + if parents: + self.fs.makedirs(self._path, exist_ok=exist_ok) + return + try: + self.fs.mkdir(self._path) + except FileExistsError: + if exist_ok and self.is_dir(): + return + raise + except LittleFSError as exc: + if exc.code == _EEXIST and exist_ok and self.is_dir(): + return + raise + + def rmdir(self) -> None: + """Remove this directory, which must be empty + + Delegates to :meth:`LittleFS.rmdir`, which -- unlike + :meth:`pathlib.Path.rmdir` -- does not check that the target is really a + directory. + """ + self.fs.rmdir(self._path) + + def unlink(self, missing_ok: bool = False) -> None: + """Remove this file""" + try: + self.fs.remove(self._path) + except FileNotFoundError: + if missing_ok: + return + raise + except LittleFSError as exc: + if exc.code == _ENOENT and missing_ok: + return + raise + + def rename(self, target: _StrPath) -> "LittleFSPath": + """Rename this path to *target* and return the new path + + littlefs replaces an existing destination, so :meth:`replace` is an alias + of this. + """ + target_str = _segment_to_str(target) + self.fs.rename(self._path, target_str) + return self.with_segments(target_str) + + #: Alias of :meth:`rename`: littlefs already overwrites the destination. + replace = rename + + def symlink_to(self, target: _StrPath, target_is_directory: bool = False) -> None: + """Always raises: littlefs has no symbolic links""" + raise NotImplementedError("littlefs does not support symbolic links") From cfb4cf2bd4c7c94f6fda7dbb9885db757f82b03a Mon Sep 17 00:00:00 2001 From: Ladislav Laska Date: Tue, 22 Sep 2026 14:57:05 +0200 Subject: [PATCH 2/3] Add tests for the pathlib interface. --- test/test_path.py | 140 ++++++++++++++ test/test_path_ops.py | 419 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 559 insertions(+) create mode 100644 test/test_path.py create mode 100644 test/test_path_ops.py diff --git a/test/test_path.py b/test/test_path.py new file mode 100644 index 0000000..b895146 --- /dev/null +++ b/test/test_path.py @@ -0,0 +1,140 @@ +"""Pure-path (no I/O) behaviour of :class:`littlefs.path.LittleFSPath`.""" +import sys + +import pytest + +# Below 3.9 there is no pathlib-abc to install, so skip. From 3.9 up it is a +# declared dependency, and importing it hard means a broken install fails the +# run instead of quietly skipping every test in this file. +if sys.version_info < (3, 9): + pytest.skip("the pathlib-style API requires pathlib-abc (Python 3.9+)", allow_module_level=True) + +from pathlib_abc import JoinablePath, PathInfo, ReadablePath, WritablePath, vfspath # noqa: E402 + +from littlefs import LittleFS, LittleFSPath # noqa: E402 + + +@pytest.fixture(scope="function") +def fs(): + fs = LittleFS(block_size=128, block_count=64) + yield fs + + +@pytest.fixture(scope="function") +def root(fs): + yield fs.root + + +def test_implements_the_abcs(root): + # The path ABCs are inherited; PathInfo is satisfied structurally. + assert isinstance(root, JoinablePath) + assert isinstance(root, ReadablePath) + assert isinstance(root, WritablePath) + assert isinstance(root.info, PathInfo) + + +def test_root_is_slash(root): + assert str(root) == "/" + assert vfspath(root) == "/" + assert root.name == "" + assert root.anchor == "/" + assert root.is_absolute() + + +def test_truediv_builds_absolute_path(root): + path = root / "a" / "b" / "c.txt" + assert str(path) == "/a/b/c.txt" + assert isinstance(path, LittleFSPath) + + +def test_bare_relative_paths_are_preserved(fs): + # littlefs resolves every path from the root, so a relative path behaves + # like its absolute equivalent, but the string is kept as given. + path = LittleFSPath("a/b", fs=fs) + assert str(path) == "a/b" + assert not path.is_absolute() + + +def test_derived_paths_keep_the_handle(root, fs): + assert root.fs is fs + assert (root / "a" / "b").fs is fs + assert (root / "a").parent.fs is fs + assert (root / "a" / "f.txt").with_suffix(".bin").fs is fs + + +def test_unbound_path_rejects_filesystem_access(): + path = LittleFSPath("/a") + with pytest.raises(ValueError, match="not bound to a LittleFS handle"): + path.fs + + +def test_low_level_struct_is_rejected(fs): + # Passing the low-level LFSFilesystem struct (a LittleFS handle's `.fs`) + # instead of the handle itself must fail fast with a clear message. + with pytest.raises(TypeError, match="high-level littlefs.LittleFS handle"): + LittleFSPath("/", fs=fs.fs) + + +def test_invalid_segment_type(root): + with pytest.raises(TypeError): + root / 42 + + +def test_str_and_as_posix(root): + path = root / "a" / "b" + assert str(path) == "/a/b" + assert path.as_posix() == "/a/b" + + +def test_is_not_os_pathlike(root, tmp_path): + # LittleFSPath must NOT implement __fspath__: pathlib_abc's vfsopen() tries + # the builtin open() first, so an os.PathLike path object would make + # read_text()/write_bytes() silently operate on the *host* filesystem. + assert not hasattr(root, "__fspath__") + + host_file = tmp_path / "host.txt" + host_file.write_text("host content") + leaked = LittleFSPath(host_file.as_posix(), fs=root.fs) + with pytest.raises(Exception) as excinfo: + leaked.read_text() + assert "host content" not in str(excinfo.value) + + +def test_equality_and_hash(fs): + assert (fs.root / "x") == (fs.root / "x") + assert hash(fs.root / "x") == hash(fs.root / "x") + assert (fs.root / "x") != (fs.root / "y") + assert (fs.root / "x") != "/x" + + +def test_equality_includes_the_filesystem(fs): + # The same string on two different filesystems is not the same file. This is + # what lets copy() write to the same path on another image. + other = LittleFS(block_size=128, block_count=64) + assert (fs.root / "x") != (other.root / "x") + + +def test_repr(root): + assert repr(root / "a") == "LittleFSPath('/a')" + + +def test_ordering(root): + paths = [root / "c", root / "a", root / "b"] + assert [p.name for p in sorted(paths)] == ["a", "b", "c"] + + # All four comparisons are implemented here -- the ABCs provide none of them + # -- and sorting alone would not notice three of them going missing, since + # Python falls back to the reflected operation. + a, b = root / "a", root / "b" + assert a < b and a <= b and b > a and b >= a + assert not (b < a) and not (b <= a) and not (a > b) and not (a >= b) + + +def test_subclass_keeps_its_type(fs): + class MyPath(LittleFSPath): + __slots__ = () + + path = MyPath("/", fs=fs) / "a" / "b" + assert isinstance(path, MyPath) + assert isinstance(path.parent, MyPath) + assert path.fs is fs diff --git a/test/test_path_ops.py b/test/test_path_ops.py new file mode 100644 index 0000000..295d5e8 --- /dev/null +++ b/test/test_path_ops.py @@ -0,0 +1,419 @@ +"""Filesystem operations performed through :class:`littlefs.path.LittleFSPath`.""" +import sys + +import pytest + +# Below 3.9 there is no pathlib-abc to install, so skip. From 3.9 up it is a +# declared dependency, and importing it hard means a broken install fails the +# run instead of quietly skipping every test in this file. +if sys.version_info < (3, 9): + pytest.skip("the pathlib-style API requires pathlib-abc (Python 3.9+)", allow_module_level=True) + +from littlefs import LittleFS, LittleFSPath # noqa: E402 +from littlefs.errors import LittleFSError # noqa: E402 +from littlefs.lfs import LFSStat # noqa: E402 + + +@pytest.fixture(scope="function") +def fs(): + fs = LittleFS(block_size=128, block_count=64) + yield fs + + +@pytest.fixture(scope="function") +def root(fs): + yield fs.root + + +@pytest.fixture(scope="function") +def tree(root): + """A small nested tree:: + + /top.txt + /pkg/mod.py + /pkg/notes.txt + /pkg/sub/deep.py + """ + (root / "top.txt").write_text("top") + (root / "pkg").mkdir() + (root / "pkg" / "mod.py").write_text("mod") + (root / "pkg" / "notes.txt").write_text("notes") + (root / "pkg" / "sub").mkdir() + (root / "pkg" / "sub" / "deep.py").write_text("deep") + yield root + + +# -- directories ---------------------------------------------------------------- +def test_mkdir_and_is_dir(root): + path = root / "data" + assert not path.exists() + path.mkdir() + assert path.exists() + assert path.is_dir() + assert not path.is_file() + + +def test_mkdir_exist_ok(root): + path = root / "data" + path.mkdir() + path.mkdir(exist_ok=True) + assert path.is_dir() + + +def test_mkdir_exist_ok_on_a_file_still_raises(root): + path = root / "file.txt" + path.write_text("x") + with pytest.raises((FileExistsError, LittleFSError)): + path.mkdir(exist_ok=True) + + +def test_mkdir_missing_parent_raises(root): + with pytest.raises((FileNotFoundError, LittleFSError)): + (root / "a" / "b" / "c").mkdir() + + +def test_mkdir_parents(root): + deep = root / "a" / "b" / "c" + deep.mkdir(parents=True) + assert deep.is_dir() + assert (root / "a").is_dir() + assert (root / "a" / "b").is_dir() + + +def test_mkdir_parents_exist_ok(root): + deep = root / "a" / "b" + deep.mkdir(parents=True) + with pytest.raises((FileExistsError, LittleFSError)): + deep.mkdir(parents=True) + deep.mkdir(parents=True, exist_ok=True) + + +def test_iterdir(root): + (root / "dir").mkdir() + (root / "dir" / "a.txt").write_text("a") + (root / "dir" / "b.txt").write_text("b") + (root / "dir" / "sub").mkdir() + children = sorted((root / "dir").iterdir()) + assert [p.name for p in children] == ["a.txt", "b.txt", "sub"] + assert [str(p) for p in children] == ["/dir/a.txt", "/dir/b.txt", "/dir/sub"] + assert all(p.fs is root.fs for p in children) + + +def test_iterdir_on_a_file_raises_not_a_directory(root): + path = root / "file.txt" + path.write_text("x") + with pytest.raises(NotADirectoryError): + path.iterdir() + + +def test_iterdir_on_a_missing_path_raises_file_not_found(root): + with pytest.raises(FileNotFoundError): + (root / "nope").iterdir() + + +def test_iterdir_primes_the_child_info(root, monkeypatch): + # iterdir() learns each entry's type from scandir(), so reading the + # children's info must not stat them all over again -- that saving is the + # point of using scandir, and nothing else would notice if it went away. + (root / "dir").mkdir() + for name in ("a", "b", "c"): + (root / "dir" / name).write_text(name) + + statted = [] + original = LittleFS.stat + monkeypatch.setattr(LittleFS, "stat", lambda self, path: statted.append(path) or original(self, path)) + + assert [child.info.is_file() for child in (root / "dir").iterdir()] == [True, True, True] + assert statted == [] + + +def test_iterdir_allows_mutation_while_iterating(root): + # The directory listing is materialised before the first yield, so the + # directory handle is closed and the tree can be modified during iteration. + (root / "dir").mkdir() + for name in ("a.txt", "b.txt", "c.txt"): + (root / "dir" / name).write_text(name) + for child in (root / "dir").iterdir(): + child.unlink() + assert list((root / "dir").iterdir()) == [] + + +# -- files ---------------------------------------------------------------------- +def test_write_read_text(root): + path = root / "hello.txt" + path.write_text("héllo") + assert path.read_text() == "héllo" + assert path.is_file() + assert not path.is_dir() + + +def test_write_read_bytes(root): + path = root / "blob.bin" + assert path.write_bytes(b"\x00\x01\x02") == 3 + assert path.read_bytes() == b"\x00\x01\x02" + + +def test_open_context_manager(root): + path = root / "f.txt" + with path.open("w") as fh: + fh.write("line\n") + with path.open("r") as fh: + assert fh.read() == "line\n" + + +def test_touch(root): + path = root / "t.txt" + path.touch() + assert path.is_file() + assert path.read_bytes() == b"" + path.touch() # exist_ok=True by default + + +def test_touch_does_not_truncate(root): + path = root / "t.txt" + path.write_text("keep") + path.touch() + assert path.read_text() == "keep" + + +def test_touch_exist_ok_false(root): + path = root / "t.txt" + path.touch() + with pytest.raises((FileExistsError, LittleFSError)): + path.touch(exist_ok=False) + + +def test_unlink(root): + path = root / "gone.txt" + path.write_text("x") + path.unlink() + assert not path.exists() + + +def test_unlink_missing_raises(root): + with pytest.raises((FileNotFoundError, LittleFSError)): + (root / "nope.txt").unlink() + + +def test_unlink_missing_ok(root): + (root / "nope.txt").unlink(missing_ok=True) + + +def test_rename(root): + src = root / "src.txt" + src.write_text("data") + dst = src.rename(root / "dst.txt") + assert not src.exists() + assert dst.read_text() == "data" + assert str(dst) == "/dst.txt" + assert dst.fs is root.fs + + +def test_rename_accepts_a_string(root): + src = root / "src.txt" + src.write_text("data") + assert src.rename("/dst.txt").read_text() == "data" + + +def test_replace_is_rename(root): + src = root / "src.txt" + src.write_text("new") + dst = root / "dst.txt" + dst.write_text("old") + src.replace(dst) + assert dst.read_text() == "new" + + +# -- stat / info ---------------------------------------------------------------- +def test_stat(root): + path = root / "s.txt" + path.write_text("12345") + stat = path.stat() + assert stat.size == 5 + assert stat.name == "s.txt" + assert stat.type == LFSStat.TYPE_REG + + +def test_info_on_a_file(root): + path = root / "f.txt" + path.write_text("x") + assert path.info.exists() + assert path.info.is_file() + assert not path.info.is_dir() + assert not path.info.is_symlink() + + +def test_info_on_a_directory(root): + path = root / "d" + path.mkdir() + assert path.info.exists() + assert path.info.is_dir() + assert not path.info.is_file() + + +def test_info_on_a_missing_path(root): + path = root / "nope" + assert not path.info.exists() + assert not path.info.is_dir() + assert not path.info.is_file() + + +def test_info_is_cached_but_exists_is_fresh(root): + # The PathInfo protocol explicitly permits cached results, and the ABC's + # glob/walk rely on it. The exists()/is_dir()/is_file() methods on the path + # itself always perform a fresh lookup. + path = root / "later.txt" + info = path.info + assert path.info is info # one info object per path + assert not info.exists() + path.write_text("x") + assert not info.exists() # still the cached answer + assert path.exists() # fresh lookup + assert path.is_file() + assert root.joinpath("later.txt").info.exists() # a fresh path, fresh info + + +# -- glob / rglob / walk -------------------------------------------------------- +def test_glob(tree): + assert sorted(str(p) for p in tree.glob("*.txt")) == ["/top.txt"] + assert sorted(str(p) for p in tree.glob("pkg/*.py")) == ["/pkg/mod.py"] + + +def test_glob_absolute_pattern_is_rejected(tree): + with pytest.raises(NotImplementedError): + list(tree.glob("/*.txt")) + + +@pytest.mark.parametrize( + "traverse", + [ + lambda path: path.glob("*"), + lambda path: path.glob("**/*"), + lambda path: path.glob("*.txt"), + lambda path: path.rglob("*"), + lambda path: path.walk(), + ], + ids=["glob", "glob-recursive", "glob-pattern", "rglob", "walk"], +) +def test_traversing_a_non_directory_yields_nothing(root, traverse): + # Like pathlib, traversing something that is not a listable directory yields + # nothing rather than raising. This only works because iterdir() raises + # OSError subclasses, which the ABC's globber and walk() catch. + a_file = root / "file.txt" + a_file.write_text("x") + + assert list(traverse(a_file)) == [] + assert list(traverse(root / "missing")) == [] + + +def test_walk_on_error_callback(root): + path = root / "file.txt" + path.write_text("x") + errors = [] + assert list(path.walk(on_error=errors.append)) == [] + assert [type(exc) for exc in errors] == [NotADirectoryError] + + +def test_glob_results_keep_the_handle(tree): + matches = list(tree.rglob("*.py")) + assert matches + assert all(p.fs is tree.fs for p in matches) + + +def test_rglob(tree): + assert sorted(str(p) for p in tree.rglob("*.py")) == ["/pkg/mod.py", "/pkg/sub/deep.py"] + assert sorted(str(p) for p in tree.rglob("*.txt")) == ["/pkg/notes.txt", "/top.txt"] + + +# -- copy ----------------------------------------------------------------------- +def test_copy_a_tree(tree): + copied = (tree / "pkg").copy(tree / "pkg2") + assert sorted(str(p) for p in copied.rglob("*")) == [ + "/pkg2/mod.py", + "/pkg2/notes.txt", + "/pkg2/sub", + "/pkg2/sub/deep.py", + ] + assert (copied / "sub" / "deep.py").read_text() == "deep" + + +def test_a_relative_path_reaches_the_same_file(root, fs): + (root / "logs").mkdir() + (root / "logs" / "boot.txt").write_text("ready") + relative = LittleFSPath("logs/boot.txt", fs=fs) + + assert relative.read_text() == "ready" + relative.write_text("changed") + assert (root / "logs" / "boot.txt").read_text() == "changed" + # ...while remaining a different path object, as in pathlib. + assert relative != root / "logs" / "boot.txt" + + +def test_copy_onto_the_same_file_by_another_path_is_refused(root, fs): + (root / "notes.txt").write_text("important") + # Different path, same file: comparing the paths would not catch this, so + # copy() has to resolve them. + with pytest.raises(OSError): + LittleFSPath("notes.txt", fs=fs).copy(root / "notes.txt") + assert (root / "notes.txt").read_text() == "important" + + +def test_copy_onto_itself_is_refused(root): + src = root / "src.txt" + src.write_text("payload") + with pytest.raises(OSError): + src.copy(root / "src.txt") + + +def test_copy_to_another_filesystem(root): + src = root / "src.txt" + src.write_text("payload") + other = LittleFS(block_size=128, block_count=64) + # Same path string, different filesystem: this must be allowed. + copied = src.copy(other.root / "src.txt") + assert copied.fs is other + assert copied.read_text() == "payload" + + +# -- symlinks ------------------------------------------------------------------- +def test_symlinks_are_unsupported(root): + assert not root.is_symlink() + with pytest.raises(NotImplementedError): + root.readlink() + with pytest.raises(NotImplementedError): + (root / "link").symlink_to("/target") + + +# -- end-to-end ----------------------------------------------------------------- +def test_end_to_end_roundtrip(): + """Build a tree, glob it, read it back, and mutate it through the path API.""" + fs = LittleFS(block_size=512, block_count=256) + root = fs.root + + (root / "logs").mkdir() + for day in range(3): + (root / "logs" / f"day{day}.log").write_text(f"entry {day}\n") + (root / "logs" / "archive").mkdir() + (root / "logs" / "archive" / "old.log").write_text("ancient\n") + + # The filesystem is really populated, as seen through the low-level API. + assert sorted(fs.listdir("/logs")) == ["archive", "day0.log", "day1.log", "day2.log"] + + found = sorted(root.rglob("*.log")) + assert [str(p) for p in found] == [ + "/logs/archive/old.log", + "/logs/day0.log", + "/logs/day1.log", + "/logs/day2.log", + ] + assert [p.read_text() for p in found] == ["ancient\n", "entry 0\n", "entry 1\n", "entry 2\n"] + + # Mutate: rename one, drop another, then re-glob. + (root / "logs" / "day0.log").rename(root / "logs" / "first.log") + (root / "logs" / "day2.log").unlink() + assert sorted(p.name for p in root.rglob("*.log")) == sorted(["first.log", "day1.log", "old.log"]) + + # Tear the tree down through the path API. + for path in sorted(root.rglob("*"), key=lambda p: len(str(p)), reverse=True): + path.unlink() if path.is_file() else path.rmdir() + assert list(root.iterdir()) == [] From bb97e1b18a01b538afd72dcde16e07bbdd166a55 Mon Sep 17 00:00:00 2001 From: Ladislav Laska Date: Tue, 22 Sep 2026 14:59:11 +0200 Subject: [PATCH 3/3] Add documentation to the Pathlib API. --- README.rst | 17 ++++++++ docs/api/index.rst | 9 +++++ docs/usage.rst | 99 +++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 123 insertions(+), 2 deletions(-) diff --git a/README.rst b/README.rst index bb3305f..3582f4c 100644 --- a/README.rst +++ b/README.rst @@ -59,6 +59,23 @@ steps which must be performed in C: with open('FlashMemory.bin', 'wb') as fh: fh.write(cfg.user_context.buffer) +Finally, the filesystem can be navigated with a :mod:`pathlib`-style interface, rooted at +:attr:`LittleFS.root`: + +.. code:: python + + from littlefs import LittleFS + + fs = LittleFS(block_size=512, block_count=256) + + (fs.root / 'logs').mkdir() + (fs.root / 'logs' / 'boot.txt').write_text('ready\n') + + for path in fs.root.rglob('*.txt'): + print(path, path.read_text()) + +See :ref:`doc-pathlib-api` for details. This interface requires Python 3.9 or later. + Installation ============ diff --git a/docs/api/index.rst b/docs/api/index.rst index 4a3c670..7e077c5 100644 --- a/docs/api/index.rst +++ b/docs/api/index.rst @@ -32,3 +32,12 @@ littlefs.lfs module .. automodule:: littlefs.lfs :members: :undoc-members: + + +littlefs.path module +==================== + +.. automodule:: littlefs.path + :members: + :undoc-members: + :special-members: __open_reader__, __open_writer__, __vfspath__ diff --git a/docs/usage.rst b/docs/usage.rst index ff4e64e..642f334 100644 --- a/docs/usage.rst +++ b/docs/usage.rst @@ -2,16 +2,18 @@ Usage ===== -littlefs-python offers three interfaces to the underlying littlefs library: +littlefs-python offers four interfaces to the underlying littlefs library: - A C-Style API which exposes all functions from the library using a minimal wrapper, written in Cython, to access the functions. - A pythonic high-level API which offers convenient functions similar to the ones known from the :mod:`os` standard library module. +- A :mod:`pathlib`-style API, which navigates the filesystem with path objects + instead of path strings. See :ref:`doc-pathlib-api`. - A command line tool, available as ``littlefs-python``. See :ref:`doc-cli` for more information. -Both API's can be mixed and matched if required. +These API's can be mixed and matched if required. C-Style API =========== @@ -43,3 +45,96 @@ Pythonic API While the pythonic API is working for basic operations like reading and writing files, creating and listing directories and some other functionality, it's by no means finished. Currently the usage is best explained in the :ref:`doc-examples` section. + + +.. _doc-pathlib-api: + +Pathlib-style API +================= + +.. warning:: + To use this API you need Python 3.9 or later. It is **provisional** and may + still change; see :mod:`littlefs.path` for what that rests on. + +:attr:`~littlefs.LittleFS.root` returns the filesystem root as a +:class:`~littlefs.path.LittleFSPath`, which behaves like a :class:`pathlib.Path`: + +.. code:: python + + from littlefs import LittleFS + + fs = LittleFS(block_size=512, block_count=256) + + logs = fs.root / 'logs' + logs.mkdir() + (logs / 'boot.txt').write_text('ready\n') + + for path in fs.root.rglob('*.txt'): + print(path, '->', path.read_text()) + +Every path derived from :attr:`~littlefs.LittleFS.root` -- via ``/``, +:attr:`~pathlib.PurePath.parent`, :meth:`~littlefs.path.LittleFSPath.iterdir`, glob +results and so on -- stays bound to the same filesystem, so all I/O is routed through it. +The bound handle is available as :attr:`~littlefs.path.LittleFSPath.fs`. + +On Python 3.8, importing :mod:`littlefs.path` or accessing +:attr:`~littlefs.LittleFS.root` raises :exc:`ImportError`; the rest of the package is +unaffected. + +Model +----- + +Pure path handling (``/``, :attr:`~pathlib.PurePath.parts`, +:attr:`~pathlib.PurePath.name`, :attr:`~pathlib.PurePath.stem`, +:attr:`~pathlib.PurePath.suffix`, :attr:`~pathlib.PurePath.parent`, +:meth:`~pathlib.PurePath.with_suffix`, :meth:`~pathlib.PurePath.relative_to`, +:meth:`~pathlib.PurePath.full_match`, ...) never touches the filesystem and comes +straight from the ABCs, as do ``glob``, ``rglob``, ``walk`` and ``copy``. Everything +else delegates to the bound handle: + +.. csv-table:: + :header: Path method, LittleFS method + :widths: 30, 30 + + ":meth:`~littlefs.path.LittleFSPath.open`, ``read_text``, ``read_bytes``, ``write_text``, ``write_bytes``, :meth:`~littlefs.path.LittleFSPath.touch`", ":meth:`~littlefs.LittleFS.open`" + ":meth:`~littlefs.path.LittleFSPath.stat`, :meth:`~littlefs.path.LittleFSPath.exists`, :meth:`~littlefs.path.LittleFSPath.is_file`, :meth:`~littlefs.path.LittleFSPath.is_dir`, :attr:`~littlefs.path.LittleFSPath.info`", ":meth:`~littlefs.LittleFS.stat`" + ":meth:`~littlefs.path.LittleFSPath.iterdir`", ":meth:`~littlefs.LittleFS.scandir`" + ":meth:`~littlefs.path.LittleFSPath.mkdir`", ":meth:`~littlefs.LittleFS.mkdir` / :meth:`~littlefs.LittleFS.makedirs`" + ":meth:`~littlefs.path.LittleFSPath.rmdir`, :meth:`~littlefs.path.LittleFSPath.unlink`", ":meth:`~littlefs.LittleFS.rmdir` / :meth:`~littlefs.LittleFS.remove`" + ":meth:`~littlefs.path.LittleFSPath.rename`, :meth:`~littlefs.path.LittleFSPath.replace`", ":meth:`~littlefs.LittleFS.rename`" + +Things to be aware of, mostly consequences of what littlefs itself supports: + +- littlefs resolves every path from the filesystem root, so a *relative* path reaches + the same file as its absolute equivalent: + + .. code:: python + + (fs.root / 'logs' / 'boot.txt').write_text('ready\n') + + LittleFSPath('logs/boot.txt', fs=fs).read_text() # 'ready\n' -- the same file + + The two are still distinct *paths*, though. As in :mod:`pathlib`, equality compares + the path itself, so ``LittleFSPath('logs/boot.txt', fs=fs)`` does not equal + ``fs.root / 'logs' / 'boot.txt'`` and hashes differently. Operations that ask + whether two paths lead to one file, such as + :meth:`~littlefs.path.LittleFSPath.copy`, do resolve them and will refuse to copy + a file onto itself. +- ``.`` and ``..`` are resolved by littlefs, not by the path object, so + ``'a/../b'`` reaches ``/b``. Going above the root (``'../x'``) is an error rather + than being clamped to it. +- ``rename`` overwrites an existing destination, so ``replace`` is an alias of it. +- There are no symbolic links: ``is_symlink()`` is always ``False``, and ``readlink()`` + and ``symlink_to()`` raise :exc:`NotImplementedError`. +- There are no modification times, so :meth:`~littlefs.path.LittleFSPath.touch` only + creates missing files and never updates an existing one. +- :attr:`~littlefs.path.LittleFSPath.info` caches its lookup, as the ``PathInfo`` + protocol permits and the ABC's ``glob``/``walk`` rely on. Use + :meth:`~littlefs.path.LittleFSPath.exists`, + :meth:`~littlefs.path.LittleFSPath.is_file` and + :meth:`~littlefs.path.LittleFSPath.is_dir` when an up-to-date answer is needed. +- A :class:`~littlefs.path.LittleFSPath` is deliberately **not** :class:`os.PathLike`: + a path inside littlefs has no meaning on the host filesystem, and implementing + ``__fspath__`` would let the ABCs' file-opening helper silently operate on the host + filesystem instead. +