littlefs-python 0.19.0__cp313-cp313-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/__main__.py ADDED
@@ -0,0 +1,418 @@
1
+ import argparse
2
+ from contextlib import suppress
3
+ import os
4
+ from pathlib import Path
5
+ import sys
6
+ import textwrap
7
+
8
+ from littlefs import LittleFS, __version__
9
+ from littlefs.errors import LittleFSError
10
+ from littlefs.repl import LittleFSRepl
11
+ from littlefs.context import UserContextFile, UserContext
12
+
13
+ # Dictionary mapping suffixes to their size in bytes
14
+ _suffix_map = {
15
+ "kb": 1024,
16
+ "mb": 1024**2,
17
+ "gb": 1024**3,
18
+ }
19
+
20
+
21
+ def _fs_from_args(args: argparse.Namespace, block_count=None, mount=True, context: UserContext = None) -> LittleFS:
22
+ """Build LittleFS from CLI args. Options name_max, attr_max, file_max are stored in the
23
+ superblock and must match when mounting an existing image. inline_max is format-relevant
24
+ (limiting it may improve flash usage)."""
25
+ block_count = block_count if block_count is not None else getattr(args, "block_count", 0)
26
+ kwargs = {
27
+ "block_size": args.block_size,
28
+ "block_count": block_count,
29
+ "name_max": args.name_max,
30
+ "inline_max": args.inline_max,
31
+ "attr_max": args.attr_max,
32
+ "file_max": args.file_max,
33
+ "filename_encoding": getattr(args, "filename_encoding", None),
34
+ }
35
+ return LittleFS(context=context, mount=mount, **kwargs)
36
+
37
+
38
+ def size_parser(size_str):
39
+ """Parse filesystem / block size in different formats"""
40
+ size_str = str(size_str).lower()
41
+
42
+ # Check if the string starts with '0x', which indicates a hexadecimal number
43
+ if size_str.startswith("0x"):
44
+ base = 16
45
+ size_str = size_str[2:]
46
+ else:
47
+ base = 10
48
+
49
+ # Separate the size number and suffix
50
+ for suffix, multiplier in _suffix_map.items():
51
+ if size_str.endswith(suffix):
52
+ num_part = size_str[: -len(suffix)]
53
+ return int(num_part, base) * multiplier
54
+
55
+ # Handle base units; remove base suffix
56
+ if size_str.endswith("b"):
57
+ size_str = size_str[:-1]
58
+
59
+ # If no suffix, assume it's in bytes
60
+ return int(size_str, base)
61
+
62
+
63
+ def _walk_all(root):
64
+ """Recursively yield all paths under root, following symlinks."""
65
+ for dirpath, dirnames, filenames in os.walk(root, followlinks=True):
66
+ dirpath = Path(dirpath)
67
+ for dirname in dirnames:
68
+ yield dirpath / dirname
69
+ for filename in filenames:
70
+ yield dirpath / filename
71
+
72
+
73
+ def create(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
74
+ """Create LittleFS image from file/directory contents."""
75
+ # fs_size OR block_count may be populated; make them consistent.
76
+ if args.block_count is None:
77
+ block_count = args.fs_size // args.block_size
78
+ if block_count * args.block_size != args.fs_size:
79
+ parser.error("fs-size must be a multiple of block-size.")
80
+ args.block_count = block_count
81
+ else:
82
+ args.fs_size = args.block_size * args.block_count
83
+
84
+ if args.verbose:
85
+ print("LittleFS Configuration:")
86
+ print(f" Block Size: {args.block_size:9d} / 0x{args.block_size:X}")
87
+ print(f" Image Size: {args.fs_size:9d} / 0x{args.fs_size:X}")
88
+ print(f" Block Count: {args.block_count:9d}")
89
+ print(f" Name Max: {args.name_max:9d}")
90
+ if args.inline_max:
91
+ print(f" Inline Max: {args.inline_max:9d} / 0x{args.inline_max:X}")
92
+ if args.attr_max:
93
+ print(f" Attr Max: {args.attr_max:9d}")
94
+ if args.file_max:
95
+ print(f" File Max: {args.file_max:9d}")
96
+ print(f" Image: {args.destination}")
97
+
98
+ source = Path(args.source).absolute()
99
+ if source.is_dir():
100
+ sources = list(_walk_all(source))
101
+ root = source
102
+ else:
103
+ sources = [source]
104
+ root = source.parent
105
+
106
+ fs = _fs_from_args(args)
107
+ for path in sources:
108
+ rel_path = path.relative_to(root)
109
+ if path.is_dir():
110
+ if args.verbose:
111
+ print("Adding Directory:", rel_path)
112
+ fs.mkdir(rel_path.as_posix())
113
+ else:
114
+ if args.verbose:
115
+ print("Adding File: ", rel_path)
116
+ with fs.open(rel_path.as_posix(), "wb") as dest:
117
+ dest.write(path.read_bytes())
118
+
119
+ if args.compact:
120
+ if args.verbose:
121
+ print(f"Compacting... {fs.used_block_count} / {args.block_count}")
122
+ compact_fs = _fs_from_args(args, block_count=fs.used_block_count)
123
+ for path in sources:
124
+ rel_path = path.relative_to(root)
125
+ if path.is_dir():
126
+ compact_fs.mkdir(rel_path.as_posix())
127
+ else:
128
+ with compact_fs.open(rel_path.as_posix(), "wb") as dest:
129
+ dest.write(path.read_bytes())
130
+ compact_fs.fs_grow(args.block_count)
131
+ data = compact_fs.context.buffer
132
+ if not args.no_pad:
133
+ data = data.ljust(args.fs_size, b"\xff")
134
+ else:
135
+ data = fs.context.buffer
136
+
137
+ args.destination.parent.mkdir(exist_ok=True, parents=True)
138
+ args.destination.write_bytes(data)
139
+ return 0
140
+
141
+
142
+ def _mount_from_context(parser: argparse.ArgumentParser, args: argparse.Namespace, context: UserContext) -> LittleFS:
143
+ # Block count is 0 because we don't know the size of the real image yet, the source file may be compacted (with the create --compact option).
144
+ fs = _fs_from_args(args, block_count=0, mount=False, context=context)
145
+ fs.mount()
146
+
147
+ if args.verbose:
148
+ input_image_size = context.in_size
149
+ actual_image_size = fs.block_count * args.block_size
150
+ print("LittleFS Configuration:")
151
+ print(f" Block Size: {args.block_size:9d} / 0x{args.block_size:X}")
152
+ if input_image_size != actual_image_size:
153
+ print(f" Image Size: {actual_image_size:9d} / 0x{actual_image_size:X}")
154
+ print(f" Input Image Size (compacted): {input_image_size:9d} / 0x{input_image_size:X}")
155
+ else:
156
+ print(f" Image Size: {input_image_size:9d} / 0x{input_image_size:X}")
157
+ print(f" Block Count: {fs.block_count:9d}")
158
+ print(f" Name Max: {args.name_max:9d}")
159
+ if args.inline_max:
160
+ print(f" Inline Max: {args.inline_max:9d} / 0x{args.inline_max:X}")
161
+ if args.attr_max:
162
+ print(f" Attr Max: {args.attr_max:9d}")
163
+ if args.file_max:
164
+ print(f" File Max: {args.file_max:9d}")
165
+ print(f" Image: {args.source}")
166
+
167
+ return fs
168
+
169
+
170
+ def _list(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
171
+ """List LittleFS image contents."""
172
+ source: Path = args.source
173
+ if not source.is_file():
174
+ parser.error(f"Source image '{source}' does not exist.")
175
+ context = UserContext(buffer=bytearray(source.read_bytes()))
176
+
177
+ fs = _mount_from_context(parser, args, context)
178
+
179
+ for root, dirs, files in fs.walk("/"):
180
+ if not root.endswith("/"):
181
+ root += "/"
182
+ for dir in dirs:
183
+ print(f"{root}{dir}")
184
+ for file in files:
185
+ print(f"{root}{file}")
186
+ return 0
187
+
188
+
189
+ def extract(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
190
+ """Extract LittleFS image contents to a directory."""
191
+ source: Path = args.source
192
+ if not source.is_file():
193
+ parser.error(f"Source image '{source}' does not exist.")
194
+ context = UserContext(buffer=bytearray(source.read_bytes()))
195
+
196
+ fs = _mount_from_context(parser, args, context)
197
+
198
+ root_dest = args.destination.absolute()
199
+ if not root_dest.exists():
200
+ root_dest.mkdir(parents=True)
201
+ if not root_dest.is_dir():
202
+ print("Destination must be a directory.")
203
+ return 1
204
+
205
+ for root, dirs, files in fs.walk("/"):
206
+ if not root.endswith("/"):
207
+ root += "/"
208
+ for dir in dirs:
209
+ src_path = root + dir
210
+ dst_path = root_dest / src_path[1:]
211
+ if args.verbose:
212
+ print(src_path, dst_path)
213
+ assert root_dest in dst_path.parents
214
+ dst_path.mkdir(exist_ok=True)
215
+ for file in files:
216
+ src_path = root + file
217
+ dst_path = root_dest / src_path[1:]
218
+ if args.verbose:
219
+ print(src_path, dst_path)
220
+ assert root_dest in dst_path.parents
221
+ with fs.open(src_path, "rb") as src:
222
+ dst_path.write_bytes(src.read())
223
+
224
+ return 0
225
+
226
+
227
+ def repl(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
228
+ """Inspect an existing LittleFS image through an interactive shell."""
229
+ source: Path = args.source
230
+ if not source.is_file():
231
+ parser.error(f"Source image '{source}' does not exist.")
232
+ context = UserContextFile(str(source)) # In repl we want context to be the file itself, so commands will change it
233
+
234
+ try:
235
+ try:
236
+ fs = _mount_from_context(parser, args, context)
237
+ except LittleFSError as exc:
238
+ parser.error(f"Failed to mount '{source}': {exc}")
239
+
240
+ shell = LittleFSRepl(fs)
241
+
242
+ shell.cmdloop()
243
+ finally:
244
+ if shell._mounted:
245
+ with suppress(LittleFSError):
246
+ fs.unmount()
247
+
248
+ return 0
249
+
250
+
251
+ def get_parser():
252
+ if sys.argv[0].endswith("__main__.py"):
253
+ prog = f"python -m littlefs"
254
+ else:
255
+ prog = f"littlefs-python"
256
+
257
+ parser = argparse.ArgumentParser(
258
+ prog=prog,
259
+ description=textwrap.dedent(
260
+ """\
261
+ Create, extract and inspect LittleFS filesystem images. Use one of the
262
+ commands listed below, the '-h' / '--help' option can be used on each
263
+ command to learn more about the usage.
264
+ """
265
+ ),
266
+ # formatter_class=argparse.RawTextHelpFormatter,
267
+ )
268
+ parser.add_argument("--version", action="version", version=__version__)
269
+
270
+ common_parser = argparse.ArgumentParser(add_help=False)
271
+ common_parser.add_argument("-v", "--verbose", action="count", default=0)
272
+ # Stored in superblock; must match when mounting an existing image:
273
+ common_parser.add_argument(
274
+ "--name-max",
275
+ type=size_parser,
276
+ default=255,
277
+ help="LittleFS max file path length. Defaults to LittleFS's default (255).",
278
+ )
279
+ common_parser.add_argument(
280
+ "--attr-max",
281
+ type=int,
282
+ default=0,
283
+ help="Max custom attribute size per file. Defaults to LittleFS's default (0 = use library default).",
284
+ )
285
+ common_parser.add_argument(
286
+ "--file-max",
287
+ type=int,
288
+ default=0,
289
+ help="Max number of open files. Defaults to LittleFS's default (0 = use library default).",
290
+ )
291
+ # Format option: limiting inline_max may improve flash usage.
292
+ common_parser.add_argument(
293
+ "--inline-max",
294
+ type=size_parser,
295
+ default=0,
296
+ help="Max inline file size; 0 = use library default. Limiting can improve flash usage.",
297
+ )
298
+ # Host-side encode/decode choice; never stored in the image. The same encoding
299
+ # must be used to extract an image as was used to create it, otherwise filenames
300
+ # will fail to decode or come out as mojibake.
301
+ common_parser.add_argument(
302
+ "--filename-encoding",
303
+ default=None,
304
+ help="Encoding for filenames stored in the image. Defaults to utf-8. "
305
+ "Use e.g. latin-1 or shift-jis for images whose names use a different encoding.",
306
+ )
307
+
308
+ subparsers = parser.add_subparsers(required=True, title="Available Commands", dest="command")
309
+
310
+ def add_command(handler, name="", help=""):
311
+ subparser = subparsers.add_parser(
312
+ name or handler.__name__, parents=[common_parser], help=help or handler.__doc__
313
+ )
314
+ subparser.set_defaults(func=handler)
315
+ return subparser
316
+
317
+ parser_create = add_command(create)
318
+ parser_create.add_argument(
319
+ "source",
320
+ type=Path,
321
+ help="Source file/directory-of-files to encode into a littlefs filesystem.",
322
+ )
323
+ parser_create.add_argument(
324
+ "destination",
325
+ type=Path,
326
+ nargs="?",
327
+ default=Path("lfs.bin"),
328
+ help="Output LittleFS filesystem binary image.",
329
+ )
330
+ parser_create.add_argument(
331
+ "--block-size",
332
+ type=size_parser,
333
+ required=True,
334
+ help="LittleFS block size.",
335
+ )
336
+ parser_create.add_argument(
337
+ "--compact",
338
+ action="store_true",
339
+ help="Store all data in the beginning blocks.",
340
+ )
341
+ parser_create.add_argument(
342
+ "--no-pad",
343
+ action="store_true",
344
+ help="Do not pad the binary to-size with 0xFF. Only valid with --compact.",
345
+ )
346
+ block_count_group = parser_create.add_mutually_exclusive_group(required=True)
347
+ block_count_group.add_argument(
348
+ "--block-count",
349
+ type=int,
350
+ help="LittleFS block count",
351
+ )
352
+ block_count_group.add_argument(
353
+ "--fs-size",
354
+ type=size_parser,
355
+ help="LittleFS filesystem size. Accepts byte units; e.g. 1MB and 1048576 are equivalent.",
356
+ )
357
+
358
+ parser_extract = add_command(extract)
359
+ parser_extract.add_argument(
360
+ "source",
361
+ type=Path,
362
+ help="Source LittleFS filesystem binary.",
363
+ )
364
+ parser_extract.add_argument(
365
+ "destination",
366
+ default=Path("."),
367
+ nargs="?",
368
+ type=Path,
369
+ help="Destination directory. Defaults to current directory.",
370
+ )
371
+ parser_extract.add_argument(
372
+ "--block-size",
373
+ type=size_parser,
374
+ required=True,
375
+ help="LittleFS block size.",
376
+ )
377
+
378
+ parser_list = add_command(_list, "list")
379
+ parser_list.add_argument(
380
+ "source",
381
+ type=Path,
382
+ help="Source LittleFS filesystem binary.",
383
+ )
384
+ parser_list.add_argument(
385
+ "--block-size",
386
+ type=size_parser,
387
+ required=True,
388
+ help="LittleFS block size.",
389
+ )
390
+
391
+ parser_repl = add_command(repl)
392
+ parser_repl.add_argument(
393
+ "source",
394
+ type=Path,
395
+ help="Source LittleFS filesystem binary.",
396
+ )
397
+ parser_repl.add_argument(
398
+ "--block-size",
399
+ type=size_parser,
400
+ required=True,
401
+ help="LittleFS block size.",
402
+ )
403
+
404
+ return parser
405
+
406
+
407
+ # Getting argv optionally from the caller to enable call from python (generally for testing, but could be used for other purposes)
408
+ def main(argv=None):
409
+ if argv is None:
410
+ argv = sys.argv
411
+ parser = get_parser()
412
+ parser.parse_known_args(argv[1:]) # Allows for ``littlefs-python --version``
413
+ args = parser.parse_args(argv[1:])
414
+ return args.func(parser, args)
415
+
416
+
417
+ if __name__ == "__main__":
418
+ sys.exit(main())
littlefs/context.py ADDED
@@ -0,0 +1,234 @@
1
+ import logging
2
+ import typing
3
+ import ctypes
4
+ import os
5
+
6
+ if typing.TYPE_CHECKING:
7
+ from .lfs import LFSConfig
8
+
9
+
10
+ class UserContext:
11
+ """Basic User Context Implementation"""
12
+
13
+ def __init__(self, buffsize: int = None, buffer: bytearray = None) -> None:
14
+ if buffer is not None:
15
+ self.buffer = buffer
16
+ elif buffsize is not None:
17
+ self.buffer = bytearray([0xFF] * buffsize)
18
+ else:
19
+ raise ValueError("Either buffsize or buffer must be provided")
20
+ self.in_size = len(self.buffer)
21
+
22
+ def read(self, cfg: "LFSConfig", block: int, off: int, size: int) -> bytearray:
23
+ """read data
24
+
25
+ Parameters
26
+ ----------
27
+ cfg : ~littlefs.lfs.LFSConfig
28
+ Filesystem configuration object
29
+ block : int
30
+ Block number to read
31
+ off : int
32
+ Offset from start of block
33
+ size : int
34
+ Number of bytes to read.
35
+ """
36
+ logging.getLogger(__name__).debug("LFS Read : Block: %d, Offset: %d, Size=%d" % (block, off, size))
37
+ start = block * cfg.block_size + off
38
+ end = start + size
39
+ return self.buffer[start:end]
40
+
41
+ def prog(self, cfg: "LFSConfig", block: int, off: int, data: bytes) -> int:
42
+ """program data
43
+
44
+ Parameters
45
+ ----------
46
+ cfg : ~littlefs.lfs.LFSConfig
47
+ Filesystem configuration object
48
+ block : int
49
+ Block number to program
50
+ off : int
51
+ Offset from start of block
52
+ data : bytes
53
+ Data to write
54
+ """
55
+ logging.getLogger(__name__).debug("LFS Prog : Block: %d, Offset: %d, Data=%r" % (block, off, data))
56
+ start = block * cfg.block_size + off
57
+ end = start + len(data)
58
+ self.buffer[start:end] = data
59
+ return 0
60
+
61
+ def erase(self, cfg: "LFSConfig", block: int) -> int:
62
+ """Erase a block
63
+
64
+ Parameters
65
+ ----------
66
+ cfg : ~littlefs.lfs.LFSConfig
67
+ Filesystem configuration object
68
+ block : int
69
+ Block number to read
70
+ """
71
+ logging.getLogger(__name__).debug("LFS Erase: Block: %d" % block)
72
+ start = block * cfg.block_size
73
+ end = start + cfg.block_size
74
+ self.buffer[start:end] = [0xFF] * cfg.block_size
75
+ return 0
76
+
77
+ def sync(self, cfg: "LFSConfig") -> int:
78
+ """Sync cached data
79
+
80
+ Parameters
81
+ ----------
82
+ cfg : ~littlefs.lfs.LFSConfig
83
+ Filesystem configuration object
84
+ """
85
+ return 0
86
+
87
+
88
+ class UserContextFile(UserContext):
89
+ """File-backed context using the standard library"""
90
+
91
+ def __init__(self, file_path: str, *, create: bool = False) -> None:
92
+ mode = "r+b"
93
+ if not os.path.exists(file_path):
94
+ if not create:
95
+ raise FileNotFoundError(f"Context file '{file_path}' does not exist")
96
+ mode = "w+b"
97
+
98
+ self._path = file_path
99
+ self._fh = open(file_path, mode)
100
+ self.in_size = os.path.getsize(file_path)
101
+
102
+ def read(self, cfg: "LFSConfig", block: int, off: int, size: int) -> bytearray:
103
+ logging.getLogger(__name__).debug("LFS Read : Block: %d, Offset: %d, Size=%d" % (block, off, size))
104
+ start = block * cfg.block_size + off
105
+ self._fh.seek(start)
106
+ data = self._fh.read(size)
107
+
108
+ if len(data) < size:
109
+ data += b"\xff" * (size - len(data))
110
+
111
+ return bytearray(data)
112
+
113
+ def prog(self, cfg: "LFSConfig", block: int, off: int, data: bytes) -> int:
114
+ logging.getLogger(__name__).debug("LFS Prog : Block: %d, Offset: %d, Data=%r" % (block, off, data))
115
+ start = block * cfg.block_size + off
116
+ self._fh.seek(start)
117
+ self._fh.write(data)
118
+ return 0
119
+
120
+ def erase(self, cfg: "LFSConfig", block: int) -> int:
121
+ logging.getLogger(__name__).debug("LFS Erase: Block: %d" % block)
122
+ start = block * cfg.block_size
123
+ self._fh.seek(start)
124
+ self._fh.write(b"\xff" * cfg.block_size)
125
+ return 0
126
+
127
+ def sync(self, cfg: "LFSConfig") -> int:
128
+ self._fh.flush()
129
+ os.fsync(self._fh.fileno())
130
+ return 0
131
+
132
+ def close(self) -> None:
133
+ if not self._fh.closed:
134
+ self._fh.close()
135
+
136
+ def __del__(self):
137
+ try:
138
+ self.close()
139
+ except Exception:
140
+ pass
141
+
142
+
143
+ try:
144
+ import win32file
145
+ except ImportError:
146
+ win32file = None
147
+
148
+
149
+ class UserContextWinDisk(UserContext):
150
+ """Windows disk/file context"""
151
+
152
+ def __init__(self, disk_path: str) -> None:
153
+ self.device = None #
154
+ # if the user does not have the pywin
155
+ if win32file == None:
156
+ raise ImportError(
157
+ "Unable to import 'win32file'. This module is required for Windows-specific functionality. Please ensure you are running on a Windows platform or install 'pywin32' using: 'pip install pywin32'."
158
+ )
159
+ self.device = win32file.CreateFile(
160
+ disk_path, win32file.GENERIC_READ | win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ, None, win32file.OPEN_EXISTING, 0, None
161
+ )
162
+ if self.device == win32file.INVALID_HANDLE_VALUE:
163
+ raise IOError("Could not open disk %s" % disk_path)
164
+ self.in_size = win32file.GetFileSize(self.device)
165
+
166
+ def read(self, cfg: "LFSConfig", block: int, off: int, size: int) -> bytearray:
167
+ """read data
168
+
169
+ Parameters
170
+ ----------
171
+ cfg : ~littlefs.lfs.LFSConfig
172
+ Filesystem configuration object
173
+ block : int
174
+ Block number to read
175
+ off : int
176
+ Offset from start of block
177
+ size : int
178
+ Number of bytes to read.
179
+ """
180
+ logging.getLogger(__name__).debug("LFS Read : Block: %d, Offset: %d, Size=%d" % (block, off, size))
181
+ start = block * cfg.block_size + off
182
+
183
+ win32file.SetFilePointer(self.device, start, win32file.FILE_BEGIN)
184
+ buffer = ctypes.create_string_buffer(size)
185
+ win32file.ReadFile(self.device, buffer)
186
+ # store the data in the buffer and close the buffer
187
+ data = buffer.raw
188
+ return data
189
+
190
+ def prog(self, cfg: "LFSConfig", block: int, off: int, data: bytes) -> int:
191
+ """program data
192
+
193
+ Parameters
194
+ ----------
195
+ cfg : ~littlefs.lfs.LFSConfig
196
+ Filesystem configuration object
197
+ block : int
198
+ Block number to program
199
+ off : int
200
+ Offset from start of block
201
+ data : bytes
202
+ Data to write
203
+ """
204
+ logging.getLogger(__name__).debug("LFS Prog : Block: %d, Offset: %d, Data=%r" % (block, off, data))
205
+ start = block * cfg.block_size + off
206
+
207
+ win32file.SetFilePointer(self.device, start, win32file.FILE_BEGIN)
208
+ win32file.WriteFile(self.device, data)
209
+ return 0
210
+
211
+ def erase(self, cfg: "LFSConfig", block: int) -> int:
212
+ """Erase a block
213
+
214
+ Parameters
215
+ ----------
216
+ cfg : ~littlefs.lfs.LFSConfig
217
+ Filesystem configuration object
218
+ block : int
219
+ Block number to read
220
+ """
221
+ logging.getLogger(__name__).debug("LFS Erase: Block: %d" % block)
222
+ start = block * cfg.block_size
223
+
224
+ win32file.SetFilePointer(self.device, start, win32file.FILE_BEGIN)
225
+ win32file.WriteFile(self.device, b'\xff' * cfg.block_size)
226
+ return 0
227
+
228
+ def sync(self, cfg: "LFSConfig") -> int:
229
+ win32file.FlushFileBuffers(self.device)
230
+ return 0
231
+
232
+ def __del__(self):
233
+ if self.device != None:
234
+ win32file.CloseHandle(self.device)
littlefs/errors.py ADDED
@@ -0,0 +1,37 @@
1
+ from enum import IntEnum
2
+
3
+
4
+ class LittleFSError(Exception):
5
+ class Error(IntEnum):
6
+ LFS_ERR_OK = 0 # No error
7
+ LFS_ERR_IO = -5 # Error during device operation
8
+ LFS_ERR_CORRUPT = -84 # Corrupted
9
+ LFS_ERR_NOENT = -2 # No directory entry
10
+ LFS_ERR_EXIST = -17 # Entry already exists
11
+ LFS_ERR_NOTDIR = -20 # Entry is not a dir
12
+ LFS_ERR_ISDIR = -21 # Entry is a dir
13
+ LFS_ERR_NOTEMPTY = -39 # Dir is not empty
14
+ LFS_ERR_BADF = -9 # Bad file number
15
+ LFS_ERR_FBIG = -27 # File too large
16
+ LFS_ERR_INVAL = -22 # Invalid parameter
17
+ LFS_ERR_NOSPC = -28 # No space left on device
18
+ LFS_ERR_NOMEM = -12 # No more memory available
19
+ LFS_ERR_NOATTR = -61 # No data/attr available
20
+ LFS_ERR_NAMETOOLONG = -36 # File name too long
21
+
22
+ def __init__(self, code: int):
23
+ super().__init__()
24
+ self.code = code
25
+
26
+ @property
27
+ def name(self) -> str:
28
+ try:
29
+ return self.Error(self.code).name
30
+ except ValueError:
31
+ return "ERR_UNKNOWN"
32
+
33
+ def __repr__(self) -> str:
34
+ return "<%s(%d)>" % (self.__class__.__name__, self.code)
35
+
36
+ def __str__(self) -> str:
37
+ return "LittleFSError %d: %s" % (self.code, self.name)
Binary file