Skip to content

Commit

Permalink
add recursive=False flag to remove method (#65)
Browse files Browse the repository at this point in the history
  • Loading branch information
BrianPugh authored Dec 1, 2023
1 parent 6123c35 commit e72b864
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
25 changes: 18 additions & 7 deletions src/littlefs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ def makedirs(self, name: str, exist_ok=False):
continue
raise e

def remove(self, path: str) -> int:
def remove(self, path: str, recursive: bool = False) -> None:
"""Remove a file or directory
If the path to remove is a directory, the directory must be empty.
Expand All @@ -277,16 +277,27 @@ def remove(self, path: str) -> int:
----------
path : str
The path to the file or directory to remove.
recursive: bool
If ``true`` and ``path`` is a directory, recursively remove all children files/folders.
"""
try:
return lfs.remove(self.fs, path)
lfs.remove(self.fs, path)
return
except errors.LittleFSError as e:
if e.code == -2:
msg = "[LittleFSError {:d}] No such file or directory: '{:s}'.".format(
e.code, path
)
if e.code == LittleFSError.Error.LFS_ERR_NOENT:
msg = "[LittleFSError {:d}] No such file or directory: '{:s}'.".format(e.code, path)
raise FileNotFoundError(msg) from e
raise e
elif e.code == LittleFSError.Error.LFS_ERR_NOTEMPTY and recursive:
# We want to recursively delete the ``path`` directory.
# Handled below to reduce amount of logic in ``except`` handler.
pass
else:
raise e

# Recursively delete the ``path`` directory
for elem in self.scandir(path):
self.remove(path + "/" + elem.name, recursive=True)
lfs.remove(self.fs, path)

def removedirs(self, name):
"""Remove directories recursively
Expand Down
9 changes: 8 additions & 1 deletion test/test_remove_rename.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,13 @@ def test_remove(fs):
assert '/dir/directroy/' in str(excinfo.value)


def test_remove_recursive(fs):
fs.remove("/dir", recursive=True)
with pytest.raises(errors.LittleFSError) as excinfo:
fs.stat("/dir")
assert "LittleFSError -2" in str(excinfo.value)


def test_removedirs(fs):
fs.removedirs('/dir/sub/file.txt')
assert set(fs.listdir('/dir')) == {'emptyA', 'emptyB', 'file.txt'}
Expand All @@ -75,4 +82,4 @@ def test_rename(fs: LittleFS):
files_in_dir = fs.listdir('/dir')

assert 'sub' not in files_in_dir
assert 'sub_renamed' in files_in_dir
assert 'sub_renamed' in files_in_dir

0 comments on commit e72b864

Please sign in to comment.