Skip to content

Commit a7eee37

Browse files
committed
fix(remove-path): prune empty parent directories recursively
Signed-off-by: Acuspeedster <arnavrajsingh@gmail.com>
1 parent 0e354a5 commit a7eee37

2 files changed

Lines changed: 26 additions & 4 deletions

File tree

tests/trestle/core/models/remove_path_action_test.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,3 +95,23 @@ def test_remove_path_magic_methods(tmp_path):
9595

9696
action_desc = rpa.to_string()
9797
assert action_desc == f'{rpa.get_type()} {tmp_data_dir}'
98+
99+
100+
def test_remove_path_prunes_empty_parent_dirs(tmp_path: pathlib.Path) -> None:
101+
"""Test remove path deletes empty parent directories recursively."""
102+
tmp_data_dir = tmp_path.joinpath('data')
103+
nested_dir = tmp_data_dir.joinpath('nested1').joinpath('nested2')
104+
tmp_data_file = nested_dir.joinpath('readme.md')
105+
test_utils.ensure_trestle_config_dir(tmp_path)
106+
nested_dir.mkdir(exist_ok=True, parents=True)
107+
108+
with open(tmp_data_file, 'a+', encoding=const.FILE_ENCODING) as fp:
109+
fp.write('DUMMY DATA')
110+
111+
rpa = RemovePathAction(tmp_data_file)
112+
rpa.execute()
113+
114+
assert tmp_data_file.exists() is False
115+
assert nested_dir.exists() is False
116+
assert nested_dir.parent.exists() is False
117+
assert tmp_data_dir.exists() is False

trestle/core/models/actions.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -358,11 +358,13 @@ def execute(self) -> None:
358358

359359
trash.store(self._sub_path, True)
360360

361-
# check if parent folder is empty and if so delete
362-
parent_dir = pathlib.Path(os.path.dirname(self._sub_path))
363-
files = list(parent_dir.iterdir())
364-
if not files:
361+
# check if parent folders are empty and if so delete them recursively up to the project root
362+
parent_dir = self._sub_path.parent
363+
while parent_dir != self._trestle_project_root:
364+
if list(parent_dir.iterdir()):
365+
break
365366
trash.store(parent_dir, True)
367+
parent_dir = parent_dir.parent
366368
self._mark_executed()
367369

368370
def rollback(self) -> None:

0 commit comments

Comments
 (0)