littlefs-python 0.19.0__cp314-cp314-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
littlefs/__init__.py ADDED
@@ -0,0 +1,519 @@
1
+ import io
2
+ import warnings
3
+ from typing import TYPE_CHECKING, List, Tuple, Iterator, IO, Union, Optional
4
+
5
+ try:
6
+ from importlib_metadata import version, PackageNotFoundError
7
+ except ImportError:
8
+ from importlib.metadata import version, PackageNotFoundError
9
+
10
+
11
+ from . import errors, lfs
12
+ from .lfs import (
13
+ __LFS_DISK_VERSION__,
14
+ __LFS_VERSION__,
15
+ LFSConfig,
16
+ LFSFilesystem,
17
+ LFSFile,
18
+ LFSDirectory,
19
+ LFSFileFlag,
20
+ LFSStat,
21
+ LFSFSStat,
22
+ )
23
+ from .errors import LittleFSError
24
+
25
+ __all__ = [
26
+ "FileHandle",
27
+ "LFSConfig",
28
+ "LFSDirectory",
29
+ "LFSFSStat",
30
+ "LFSFile",
31
+ "LFSFileFlag",
32
+ "LFSFilesystem",
33
+ "LFSStat",
34
+ "LittleFS",
35
+ "LittleFSError",
36
+ "UserContext",
37
+ "UserContextFile",
38
+ "UserContextWinDisk",
39
+ "__LFS_DISK_VERSION__",
40
+ "__LFS_VERSION__",
41
+ "errors",
42
+ "lfs",
43
+ ]
44
+
45
+
46
+ try:
47
+ __version__ = version("littlefs-python")
48
+ except PackageNotFoundError:
49
+ # Package not installed
50
+ pass
51
+
52
+ from .context import UserContext, UserContextFile, UserContextWinDisk
53
+
54
+ if TYPE_CHECKING:
55
+ from .lfs import LFSStat
56
+
57
+
58
+ class LittleFS:
59
+ """Littlefs file system"""
60
+
61
+ def __init__(
62
+ self,
63
+ context: Optional["UserContext"] = None,
64
+ mount=True,
65
+ filename_encoding: Optional[str] = None,
66
+ **kwargs,
67
+ ) -> None:
68
+ """
69
+ Parameters
70
+ ----------
71
+ filename_encoding : Optional[str]
72
+ Encoding used to encode/decode filenames passed to and returned by
73
+ the filesystem. littlefs stores names as opaque byte strings, so this
74
+ is a free choice. Defaults to :data:`littlefs.lfs.FILENAME_ENCODING`
75
+ (``"utf-8"``). Set this when reading an image whose names were written
76
+ with a different encoding (e.g. ``"latin-1"`` or ``"shift-jis"``).
77
+
78
+ Note that littlefs's ``name_max`` limit is measured in *encoded
79
+ bytes*, not characters. With a multi-byte encoding such as UTF-8, a
80
+ single non-ASCII character consumes 2-4 bytes, so a name can exceed
81
+ ``name_max`` (default 255) well before it looks long.
82
+ """
83
+ self.filename_encoding = filename_encoding or lfs.FILENAME_ENCODING
84
+ self.cfg = lfs.LFSConfig(context=context, **kwargs)
85
+ self.fs = lfs.LFSFilesystem()
86
+
87
+ if mount:
88
+ try:
89
+ self.mount()
90
+ except errors.LittleFSError:
91
+ self.format()
92
+ self.mount()
93
+
94
+ @property
95
+ def block_count(self) -> int:
96
+ return self.fs.block_count
97
+
98
+ @property
99
+ def used_block_count(self) -> int:
100
+ return lfs.fs_size(self.fs)
101
+
102
+ @property
103
+ def context(self) -> "UserContext":
104
+ """User context of the file system"""
105
+ return self.cfg.user_context
106
+
107
+ def format(self) -> int:
108
+ """Format the underlying buffer"""
109
+ if self.cfg.block_count == 0:
110
+ # ``lfs.format`` looks at cfg's block_count.
111
+ # Cannot autodetect size when formatting.
112
+ raise LittleFSError(LittleFSError.Error.LFS_ERR_INVAL)
113
+ return lfs.format(self.fs, self.cfg)
114
+
115
+ def mount(self) -> int:
116
+ """Mount the underlying buffer"""
117
+ return lfs.mount(self.fs, self.cfg)
118
+
119
+ def unmount(self) -> int:
120
+ """Unmount the underlying buffer"""
121
+ return lfs.unmount(self.fs)
122
+
123
+ def fs_mkconsistent(self) -> int:
124
+ """Attempt to make the filesystem consistent and ready for writing"""
125
+ return lfs.fs_mkconsistent(self.fs)
126
+
127
+ def fs_grow(self, block_count: int) -> int:
128
+ """WARNING: does not modify underlying ``self.context``.
129
+
130
+ Must be done externally.
131
+ """
132
+ if block_count < self.block_count:
133
+ raise ValueError(
134
+ f"Supplied block_count='{block_count}' cannot be smaller than current block_count {self.block_count}"
135
+ )
136
+
137
+ return lfs.fs_grow(self.fs, block_count)
138
+
139
+ def fs_stat(self) -> "LFSFSStat":
140
+ """Get the status of the filesystem"""
141
+ return lfs.fs_stat(self.fs)
142
+
143
+ def fs_gc(self):
144
+ return lfs.fs_gc(self.fs)
145
+
146
+ def open(
147
+ self, fname: str, mode="r", buffering: int = -1, encoding: str = None, errors: str = None, newline: str = None
148
+ ) -> IO:
149
+ """Open a file.
150
+
151
+ :attr:`mode` is an optional string that specifies the mode in which
152
+ the file is opened and is analogous to the built-in :func:`io.open`
153
+ function. Files opened in text mode (default) will take and return
154
+ `str` objects. Files opened in binary mode will take and return
155
+ byte-like objects.
156
+
157
+ Parameters
158
+ ----------
159
+ fname : str
160
+ The path to the file to open.
161
+ mode : str
162
+ Specifies the mode in which the file is opened.
163
+ buffering : int
164
+ Specifies the buffering policy. Pass `0` to disable buffering in
165
+ binary mode.
166
+ encoding : str
167
+ Text encoding to use. (text mode only)
168
+ errors : str
169
+ Specifies how encoding and decoding errors are to be handled. (text mode only)
170
+ newline : str
171
+ Controls how universal newlines mode works. (text mode only)
172
+ """
173
+
174
+ # Parse mode
175
+ creating = False
176
+ reading = False
177
+ writing = False
178
+ appending = False
179
+ updating = False
180
+
181
+ binary = False
182
+ text = False
183
+
184
+ for ch in mode:
185
+ if ch == "x":
186
+ creating = True
187
+ elif ch == "r":
188
+ reading = True
189
+ elif ch == "w":
190
+ writing = True
191
+ elif ch == "a":
192
+ appending = True
193
+ elif ch == "+":
194
+ updating = True
195
+ elif ch == "b":
196
+ binary = True
197
+ elif ch == "t":
198
+ text = True
199
+ else:
200
+ raise ValueError(f"invalid mode: '{mode}'")
201
+
202
+ if text and binary:
203
+ raise ValueError("can't have text and binary mode at once")
204
+
205
+ exclusive_modes = (creating, reading, writing, appending)
206
+
207
+ if sum(int(m) for m in exclusive_modes) > 1:
208
+ raise ValueError("must have exactly one of create/read/write/append mode")
209
+
210
+ if binary:
211
+ if encoding is not None:
212
+ raise ValueError("binary mode doesn't take an encoding argument")
213
+
214
+ if errors is not None:
215
+ raise ValueError("binary mode doesn't take an errors argument")
216
+
217
+ if newline is not None:
218
+ raise ValueError("binary mode doesn't take a newline argument")
219
+
220
+ if buffering == 1:
221
+ msg = (
222
+ "line buffering (buffering=1) isn't supported in "
223
+ "binary mode, the default buffer size will be used"
224
+ )
225
+ warnings.warn(msg, RuntimeWarning)
226
+ buffering = -1
227
+
228
+ try:
229
+ fh = lfs.file_open(self.fs, fname, mode, self.filename_encoding)
230
+ except LittleFSError as e:
231
+ # Try to map to standard Python exceptions
232
+ if e.code == LittleFSError.Error.LFS_ERR_NOENT:
233
+ raise FileNotFoundError from e
234
+ elif e.code == LittleFSError.Error.LFS_ERR_ISDIR:
235
+ raise IsADirectoryError from e
236
+ elif e.code == LittleFSError.Error.LFS_ERR_EXIST:
237
+ raise FileExistsError from e
238
+ else:
239
+ raise e
240
+
241
+ raw = FileHandle(self.fs, fh)
242
+
243
+ line_buffering = False
244
+
245
+ if buffering == 1:
246
+ buffering = -1
247
+ line_buffering = True
248
+
249
+ if buffering < 0:
250
+ buffering = self.cfg.cache_size
251
+
252
+ if buffering == 0:
253
+ if not binary:
254
+ raise ValueError("can't have unbuffered text I/O")
255
+
256
+ return raw
257
+
258
+ if updating:
259
+ buffered = io.BufferedRandom(raw, buffering)
260
+ elif creating or writing or appending:
261
+ buffered = io.BufferedWriter(raw, buffering)
262
+ elif reading:
263
+ buffered = io.BufferedReader(raw, buffering)
264
+ else:
265
+ raise ValueError(f"Unknown mode: '{mode}'")
266
+
267
+ if binary:
268
+ return buffered
269
+
270
+ wrapped = io.TextIOWrapper(buffered, encoding, errors, newline, line_buffering)
271
+
272
+ return wrapped
273
+
274
+ def getattr(self, path: str, typ: Union[str, bytes, int]) -> bytes:
275
+ typ = _typ_to_uint8(typ)
276
+ return lfs.getattr(self.fs, path, typ, self.filename_encoding)
277
+
278
+ def setattr(self, path: str, typ: Union[str, bytes, int], data: bytes) -> None:
279
+ typ = _typ_to_uint8(typ)
280
+ lfs.setattr(self.fs, path, typ, data, self.filename_encoding)
281
+
282
+ def removeattr(self, path: str, typ: Union[str, bytes, int]) -> None:
283
+ typ = _typ_to_uint8(typ)
284
+ lfs.removeattr(self.fs, path, typ, self.filename_encoding)
285
+
286
+ def listdir(self, path=".") -> List[str]:
287
+ """List directory content
288
+
289
+ List the content of a directory. This function uses :meth:`scandir`
290
+ internally. Using :meth:`scandir` might be better if you are
291
+ searching for a specific file or need access to the :class:`littlefs.lfs.LFSStat`
292
+ of the files.
293
+ """
294
+ return [st.name for st in self.scandir(path)]
295
+
296
+ def mkdir(self, path: str) -> int:
297
+ """Create a new directory"""
298
+ try:
299
+ return lfs.mkdir(self.fs, path, self.filename_encoding)
300
+ except errors.LittleFSError as e:
301
+ if e.code == LittleFSError.Error.LFS_ERR_EXIST:
302
+ msg = "[LittleFSError {:d}] Cannot create a file when that file already exists: '{:s}'.".format(
303
+ e.code, path
304
+ )
305
+ raise FileExistsError(msg) from e
306
+ raise
307
+
308
+ def makedirs(self, name: str, exist_ok=False):
309
+ """Recursive directory creation function."""
310
+ parts = [p for p in name.split("/") if p]
311
+ current_name = ""
312
+ for nr, part in enumerate(parts):
313
+ current_name += "/%s" % part
314
+ try:
315
+ self.mkdir(current_name)
316
+ except FileExistsError as e:
317
+ is_last = nr == len(parts) - 1
318
+ if (not is_last) or (is_last and exist_ok):
319
+ continue
320
+ raise e
321
+
322
+ def remove(self, path: str, recursive: bool = False) -> None:
323
+ """Remove a file or directory
324
+
325
+ If the path to remove is a directory, the directory must be empty.
326
+
327
+ Parameters
328
+ ----------
329
+ path : str
330
+ The path to the file or directory to remove.
331
+ recursive: bool
332
+ If ``true`` and ``path`` is a directory, recursively remove all children files/folders.
333
+ """
334
+ try:
335
+ lfs.remove(self.fs, path, self.filename_encoding)
336
+ return
337
+ except errors.LittleFSError as e:
338
+ if e.code == LittleFSError.Error.LFS_ERR_NOENT:
339
+ msg = "[LittleFSError {:d}] No such file or directory: '{:s}'.".format(e.code, path)
340
+ raise FileNotFoundError(msg) from e
341
+ elif e.code == LittleFSError.Error.LFS_ERR_NOTEMPTY and recursive:
342
+ # We want to recursively delete the ``path`` directory.
343
+ # Handled below to reduce amount of logic in ``except`` handler.
344
+ pass
345
+ else:
346
+ raise e
347
+
348
+ # Recursively delete the ``path`` directory
349
+ for elem in self.scandir(path):
350
+ self.remove(path + "/" + elem.name, recursive=True)
351
+ lfs.remove(self.fs, path, self.filename_encoding)
352
+
353
+ def removedirs(self, name):
354
+ """Remove directories recursively
355
+
356
+ This works like :func:`remove` but if the leaf directory
357
+ is empty after the successful removal of :attr:`name`, the
358
+ function tries to recursively remove all parent directories
359
+ which are also empty.
360
+ """
361
+ parts = name.split("/")
362
+ while parts:
363
+ try:
364
+ name = "/".join(parts)
365
+ if not name:
366
+ break
367
+ self.remove("/".join(parts))
368
+ except errors.LittleFSError as e:
369
+ if e.code == LittleFSError.Error.LFS_ERR_NOTEMPTY:
370
+ break
371
+ raise e
372
+ parts.pop()
373
+
374
+ def rename(self, src: str, dst: str) -> int:
375
+ """Rename a file or directory"""
376
+ return lfs.rename(self.fs, src, dst, self.filename_encoding)
377
+
378
+ def rmdir(self, path: str) -> int:
379
+ """Remove a directory
380
+
381
+ This function is an alias for :func:`remove`
382
+ """
383
+ return self.remove(path)
384
+
385
+ def scandir(self, path=".") -> Iterator["LFSStat"]:
386
+ """List directory content"""
387
+ dh = lfs.dir_open(self.fs, path, self.filename_encoding)
388
+ try:
389
+ info = lfs.dir_read(self.fs, dh, self.filename_encoding)
390
+ while info:
391
+ if info.name not in [".", ".."]:
392
+ yield info
393
+ info = lfs.dir_read(self.fs, dh, self.filename_encoding)
394
+ finally:
395
+ lfs.dir_close(self.fs, dh)
396
+
397
+ def stat(self, path: str) -> "LFSStat":
398
+ """Get the status of a file or directory"""
399
+ return lfs.stat(self.fs, path, self.filename_encoding)
400
+
401
+ def unlink(self, path: str) -> int:
402
+ """Remove a file or directory
403
+
404
+ This function is an alias for :func:`remove`.
405
+ """
406
+ return self.remove(path)
407
+
408
+ def walk(self, top: str) -> Iterator[Tuple[str, List[str], List[str]]]:
409
+ """Generate the file names in a directory tree
410
+
411
+ Generate the file and directory names in a directory tree by
412
+ walking the tree top-down. This functions closely resembels the
413
+ behaviour of :func:`os.walk`.
414
+
415
+ Each iteration yields a tuple containing three elements:
416
+
417
+ - The root of the currently processed element
418
+ - A list of directories located in the root
419
+ - A list of filenames located in the root
420
+ """
421
+ files, dirs = [], []
422
+ for elem in self.scandir(top):
423
+ if elem.type == 1:
424
+ files.append(elem.name)
425
+ elif elem.type == 2:
426
+ dirs.append(elem.name)
427
+
428
+ yield top, dirs, files
429
+ for dirname in dirs:
430
+ newtop = "/".join((top, dirname)).replace("//", "/")
431
+ yield from self.walk(newtop)
432
+
433
+
434
+ class FileHandle(io.RawIOBase):
435
+ def __init__(self, fs, fh):
436
+ super().__init__()
437
+
438
+ self.fs = fs
439
+ self.fh = fh
440
+
441
+ def close(self):
442
+ # Base implementation is not used to avoid extra call to flush().
443
+ # LittleFS already flushes the file on close.
444
+
445
+ if not self.closed:
446
+ lfs.file_close(self.fs, self.fh)
447
+ setattr(self, "__IOBase_closed", True)
448
+
449
+ def readable(self):
450
+ return lfs.LFSFileFlag.rdonly in self.fh.flags and not self.closed
451
+
452
+ def writable(self):
453
+ return lfs.LFSFileFlag.wronly in self.fh.flags and not self.closed
454
+
455
+ def seekable(self):
456
+ self._checkClosed()
457
+ return True
458
+
459
+ def seek(self, offset, whence=io.SEEK_SET):
460
+ # Whence constants are reused from the io module. The constants have
461
+ # the same as LFS_SEEK_SET / LFS_SEEK_CUR / LFS_SEEK_END.
462
+ self._checkClosed()
463
+ return lfs.file_seek(self.fs, self.fh, offset, whence)
464
+
465
+ def tell(self):
466
+ self._checkClosed()
467
+ return lfs.file_tell(self.fs, self.fh)
468
+
469
+ def truncate(self, size=None) -> int:
470
+ self._checkClosed()
471
+
472
+ pos = self.tell()
473
+ ret = lfs.file_truncate(self.fs, self.fh, pos)
474
+
475
+ return ret
476
+
477
+ def write(self, data):
478
+ self._checkClosed()
479
+ self._checkWritable()
480
+
481
+ return lfs.file_write(self.fs, self.fh, bytes(data))
482
+
483
+ def readinto(self, b):
484
+ self._checkClosed()
485
+ self._checkReadable()
486
+
487
+ req_len = len(b)
488
+ result = lfs.file_read(self.fs, self.fh, req_len)
489
+ res_len = len(result)
490
+
491
+ b[0:res_len] = result
492
+
493
+ return res_len
494
+
495
+ def readall(self):
496
+ self._checkClosed()
497
+ self._checkReadable()
498
+
499
+ file_size = lfs.file_size(self.fs, self.fh)
500
+ file_pos = self.tell()
501
+ size = file_size - file_pos
502
+
503
+ return lfs.file_read(self.fs, self.fh, size)
504
+
505
+ def flush(self):
506
+ super().flush()
507
+ lfs.file_sync(self.fs, self.fh)
508
+
509
+
510
+ def _typ_to_uint8(typ):
511
+ try:
512
+ out = ord(typ)
513
+ except TypeError:
514
+ out = int(typ)
515
+
516
+ if not (0 <= out <= 255):
517
+ raise ValueError(f"type must be in range [0, 255]")
518
+
519
+ return out