Skip to content

Commit 6053e33

Browse files
committed
Fixing issues on Windows.
lfs.py: Use os.replace() instead of os.rename() to work on Windows. Whitespace changes due to updated ruff config.
1 parent 4180f04 commit 6053e33

File tree

8 files changed

+57
-60
lines changed

8 files changed

+57
-60
lines changed

src/mp_image_tool_esp32/argparse_typed.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
`argparse.add_argument()` which also makes the command usage easier for
1717
humans to parse from the code.
1818
"""
19+
1920
from __future__ import annotations
2021

2122
from argparse import ArgumentParser, Namespace

src/mp_image_tool_esp32/argtypes.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
- `unsplit(arglist)`: Join a list of lists of strings or ints back into a single
1111
string.
1212
"""
13+
1314
from __future__ import annotations
1415

1516
import re

src/mp_image_tool_esp32/layouts.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
- `print_table(table)`: Print a detailed description of the partition table.
1414
"""
1515

16-
1716
import csv
1817

1918
from rich import box

src/mp_image_tool_esp32/lfs.py

Lines changed: 48 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ def flush(self) -> None:
122122

123123
# Join contiguous blocks together into larger blocks for writing
124124
def group_blocks(
125-
items: Iterable[tuple[int, bytes]]
125+
items: Iterable[tuple[int, bytes]],
126126
) -> Iterable[tuple[int, bytes]]:
127127
return (
128128
# (start_block_number, concatenated_block_data)
@@ -215,21 +215,21 @@ def __del__(self) -> None:
215215
self.block_cache.close()
216216

217217

218-
def _is_file(fs: LittleFS, src: str | Path) -> bool:
218+
def _is_file(fs: LittleFS, path: Path) -> bool:
219219
"""Check if the path is a file."""
220-
src = Path(src)
221-
return (fs.stat(src.as_posix()).type & LFSStat.TYPE_REG) != 0
220+
return (fs.stat(path.as_posix()).type & LFSStat.TYPE_REG) != 0
222221

223222

224-
def _is_dir(fs: LittleFS, src: Path) -> bool:
223+
def _is_dir(fs: LittleFS, path: Path) -> bool:
225224
"""Check if the path is a directory."""
226-
return (fs.stat(src.as_posix()).type & LFSStat.TYPE_DIR) != 0
225+
return (fs.stat(path.as_posix()).type & LFSStat.TYPE_DIR) != 0
227226

228227

229228
def _get_file(fs: LittleFS, src: Path, dst: Path) -> None:
230229
"""Copy a file from the LittleFS filesystem to the local filesystem."""
231230
with fs.open(src.as_posix(), "rb") as f:
232231
dst.write_bytes(f.read())
232+
assert fs.stat(src.as_posix()).size == dst.stat().st_size
233233

234234

235235
def _put_file(fs: LittleFS, src: Path, dst: Path) -> None:
@@ -242,6 +242,7 @@ def _put_file(fs: LittleFS, src: Path, dst: Path) -> None:
242242
pass
243243
with fs.open(dst.as_posix(), "wb") as f:
244244
f.write(src.read_bytes())
245+
assert fs.stat(dst.as_posix()).size == src.stat().st_size
245246

246247

247248
def littlefs(part: BinaryIO, block_count: int = 0) -> LittleFS:
@@ -284,7 +285,7 @@ def run_command(self, command: str, args: list[str]) -> None:
284285
else:
285286
raise ValueError(f"Unknown --fs command '{self.command}'")
286287

287-
def vfs_files(self, names: Iterable[str]) -> Iterator[tuple[LittleFS, str, str]]:
288+
def vfs_files(self, names: Iterable[str]) -> Iterator[tuple[LittleFS, Path, str]]:
288289
"""A generator to yield LittleFS filesystems for a list of partition names.
289290
Yields a tuple of the filesystem, the file name, and the partition name."""
290291
partname: str = "vfs"
@@ -293,7 +294,7 @@ def vfs_files(self, names: Iterable[str]) -> Iterator[tuple[LittleFS, str, str]]
293294
try:
294295
with self.firmware.partition(partname) as part:
295296
with lfs_mounted(part) as fs:
296-
yield fs, name, partname
297+
yield fs, Path(name), partname
297298
except (ValueError, LittleFSError):
298299
# Skip partition if not present in firmware file or if no lfs
299300
pass
@@ -351,10 +352,8 @@ def do_df(self) -> None:
351352

352353
def do_grow(self) -> None:
353354
"""Resize/grow the LittleFS filesystem."""
354-
name, size = (
355-
(self.args or ["vfs"])[0],
356-
(int(IntArg(self.args[1])) if len(self.args) > 1 else 0),
357-
)
355+
name: str = (self.args or ["vfs"])[0]
356+
size: int = int(IntArg(self.args[1])) if len(self.args) > 1 else 0
358357
with self.firmware.partition(name) as p:
359358
with lfs_mounted(p) as fs:
360359
old, new = fs.block_count, size or p.part.size // BLOCK_SIZE
@@ -364,104 +363,103 @@ def do_grow(self) -> None:
364363

365364
def do_ls(self) -> None:
366365
"""Recursively list the contents of a directory on the LittleFS filesystem."""
367-
for fs, name, part in self.vfs_files(self.args or ["/"]):
368-
log.action(f"ls '{part}:{name}':")
369-
src = Path(name)
370-
for root, subdirs, files in fs.walk(str(src)):
371-
d = Path(root).relative_to(src)
366+
for fs, path, part in self.vfs_files(self.args or [""]):
367+
log.action(f"ls '{part}:{path.as_posix()}'")
368+
for root, subdirs, files in fs.walk(path.as_posix()):
369+
d = Path(root).relative_to(path)
372370
for f in (d / f for f in files):
373-
print(f"{f}")
371+
print(f.as_posix())
374372
for f in (d / f for f in subdirs):
375-
print(f"{f}/")
373+
print(f.as_posix() + "/")
376374

377375
def do_cat(self) -> None:
378376
"""Print out the contents of a file on the LittleFS filesystem."""
379-
for fs, name, part in self.vfs_files(self.args):
380-
log.action(f"cat '{part}:{name}':")
381-
if not _is_file(fs, Path(name)):
382-
raise FileNotFoundError(f"{name} is not a file.")
383-
with fs.open(name, "r") as f:
377+
for fs, path, part in self.vfs_files(self.args):
378+
log.action(f"cat '{part}:{path.as_posix()}'")
379+
if not _is_file(fs, path):
380+
raise FileNotFoundError(f"{path.as_posix()} is not a file.")
381+
with fs.open(path.as_posix(), "r") as f:
384382
print(f.read(), end="")
385383

386384
def do_mkdir(self) -> None:
387385
"""Create a directory on the LittleFS filesystem."""
388-
for fs, name, part in self.vfs_files(self.args):
389-
log.action(f"mkdir '{part}:{name}':")
390-
fs.makedirs(name, exist_ok=True)
386+
for fs, path, part in self.vfs_files(self.args):
387+
log.action(f"mkdir '{part}:{path.as_posix()}'")
388+
fs.makedirs(path.as_posix(), exist_ok=True)
389+
assert _is_dir(fs, path)
391390

392391
def do_rm(self) -> None:
393392
"""Remove a file or directory from the LittleFS filesystem."""
394-
for fs, name, part in self.vfs_files(self.args):
395-
log.action(f"rm '{part}:{name}':")
396-
fs.remove(name, recursive=True)
393+
for fs, path, part in self.vfs_files(self.args):
394+
log.action(f"rm '{part}:{path}'")
395+
fs.remove(path.as_posix(), recursive=True)
397396

398397
def do_rename(self) -> None:
399398
"""Rename a file or directory on the LittleFS filesystem."""
400399
if len(self.args) != 2:
401400
raise ValueError("'--fs rename' requires two arguments")
402401
names = self.vfs_files(self.args)
403-
fs, name1, part1 = next(names)
404-
fs, name2, part2 = next(names)
402+
fs, path1, part1 = next(names)
403+
fs, path2, part2 = next(names)
405404
if part1 != part2:
406405
raise ValueError("'--fs rename' Both partitions must be the same")
407-
log.action(f"rename '{part1}:{name1}' -> '{name2}:")
408-
fs.rename(name1, name2)
406+
log.action(f"rename '{part1}:{path1.as_posix()}' -> '{path2.as_posix()}")
407+
fs.rename(path1.as_posix(), path2.as_posix())
409408
for _ in names: # Finish the generator
410409
pass
411410

412411
def do_get(self) -> None:
413412
"""Copy a file or directory from the LittleFS filesystem to the local filesystem."""
414413
destname = self.args.pop(-1) if len(self.args) > 1 else "."
415-
for fs, name, part in self.vfs_files(self.args):
416-
log.action(f"get '{part}:{name}' -> '{destname}:")
414+
for fs, path, part in self.vfs_files(self.args):
415+
log.action(f"get '{part}:{path.as_posix()}' -> '{destname}")
417416

418-
source, dest = Path(name), Path(destname)
417+
source, dest = Path(path), Path(destname)
419418
if _is_file(fs, source): # Copy a single file
420419
# If the destination is a directory, copy the file into it
421420
if dest.is_dir():
422421
dest /= source.name
423422
_get_file(fs, source, dest)
424423
continue
425424

426-
print(f"{source} -> {dest}")
425+
print(f"{source.as_posix()} -> {dest}")
427426
dest.mkdir(exist_ok=True)
428-
for root, subdirs, files in fs.walk(str(source)):
427+
for root, subdirs, files in fs.walk(source.as_posix()):
429428
srcdir = Path(root)
430429
dstdir = dest / srcdir.relative_to(source)
431430
for src, dst in ((srcdir / f, dstdir / f) for f in files):
432-
print(f"{src} -> {dst}")
431+
print(f"{src.as_posix()} -> {dst}")
433432
_get_file(fs, src, dst)
434433
for src, dst in ((srcdir / f, dstdir / f) for f in subdirs):
435-
print(f"{src}/ -> {dst}/")
434+
print(f"{src.as_posix()}/ -> {dst}{os.sep}")
436435
dst.mkdir(exist_ok=True)
437436

438437
def do_put(self) -> None:
439438
"""Copy a file or directory from the local filesystem to the LittleFS filesystem."""
440439
destname = self.args.pop(-1) if len(self.args) > 1 else "."
441-
for fs, destname, part in self.vfs_files([destname]):
442-
log.action(f"put '{' '.join(self.args)}' -> '{part}:{destname}':")
443-
440+
for fs, destpath, part in self.vfs_files([destname]):
444441
for name in self.args:
445-
source, dest = Path(name), Path(destname)
442+
log.action(f"put '{name}' -> '{part}:{destpath.as_posix()}':")
443+
source, dest = Path(name), destpath
446444
if source.is_file(): # Copy a single file
447445
# If the destination is a directory, copy the file into it
448446
if _is_dir(fs, dest):
449447
dest /= source.name
450-
print(f"{source} -> {dest}")
448+
print(f"{source} -> {dest.as_posix()}")
451449
_put_file(fs, source, dest)
452450
continue
453451

454452
dest /= source.name
455-
print(f"{source} -> {dest}")
453+
print(f"{source} -> {dest.as_posix()}")
456454
fs.makedirs(dest.as_posix(), exist_ok=True)
457-
for root, dirs, files in os.walk(str(source)):
455+
for root, dirs, files in os.walk(source):
458456
srcdir = Path(root)
459457
dstdir = dest / srcdir.relative_to(source)
460458
for src, dst in ((srcdir / f, dstdir / f) for f in files):
461-
print(f"{src} -> {dst}")
459+
print(f"{src} -> {dst.as_posix()}")
462460
_put_file(fs, src, dst)
463461
for src, dst in ((srcdir / f, dstdir / f) for f in dirs):
464-
print(f"{src}/ -> {dst}/")
462+
print(f"{src}{os.sep} -> {dst.as_posix()}/")
465463
fs.makedirs(dst.as_posix(), exist_ok=True)
466464

467465
def do_mkfs(self) -> None:

src/mp_image_tool_esp32/logger.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
# MIT License: Copyright (c) 2023 @glenn20
2-
"""A wrapper module to provide a consistent interface for logging to console.
3-
"""
2+
"""A wrapper module to provide a consistent interface for logging to console."""
43

54
import logging
65
import typing

src/mp_image_tool_esp32/main.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -172,11 +172,11 @@ def run_commands(argv: Sequence[str] | None = None) -> None:
172172
format=logger.FORMAT,
173173
handlers=[logger.richhandler],
174174
level=(
175-
logging.ERROR
176-
if args.quiet
177-
else logging.DEBUG if args.debug else logging.INFO
175+
logging.ERROR if args.quiet else
176+
logging.DEBUG if args.debug else
177+
logging.INFO
178178
),
179-
)
179+
) # fmt: skip
180180
if args.log:
181181
logger.set_logging(args.log)
182182

src/mp_image_tool_esp32/partition_table.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
Both classes include `from_bytes()` and `to_bytes()` methods to read and
1010
write from binary partiton tables in firmware files and devices.
1111
"""
12+
1213
from __future__ import annotations
1314

1415
import hashlib

src/mp_image_tool_esp32/progress_bar.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
"""A module for showing progress bars and capturing output from esptool.py.
2-
3-
"""
1+
"""A module for showing progress bars and capturing output from esptool.py."""
42

53
from __future__ import annotations
64

0 commit comments

Comments
 (0)