Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
============
Expand Down
9 changes: 9 additions & 0 deletions docs/api/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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__
99 changes: 97 additions & 2 deletions docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
===========
Expand Down Expand Up @@ -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.

3 changes: 3 additions & 0 deletions mypy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@ check_untyped_defs = True

[mypy-pytest.*]
ignore_missing_imports = True

[mypy-pathlib_abc.*]
ignore_missing_imports = True
4 changes: 4 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
36 changes: 35 additions & 1 deletion src/littlefs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"LFSStat",
"LittleFS",
"LittleFSError",
"LittleFSPath",
"UserContext",
"UserContextFile",
"UserContextWinDisk",
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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.

Expand Down
Loading
Loading