diff --git a/pyiron_workflow/files.py b/pyiron_workflow/files.py index 05c6af03..8914913b 100644 --- a/pyiron_workflow/files.py +++ b/pyiron_workflow/files.py @@ -43,8 +43,9 @@ def __init__(self, directory): def create(self): self.path.mkdir(parents=True, exist_ok=True) - def delete(self): - delete_files_and_directories_recursively(self.path) + def delete(self, only_if_empty: bool = False): + if self.is_empty() or not only_if_empty: + delete_files_and_directories_recursively(self.path) def list_content(self): return categorize_folder_items(self.path) @@ -71,6 +72,9 @@ def create_subdirectory(self, path): def create_file(self, file_name): return FileObject(file_name, self) + def is_empty(self) -> bool: + return len(self) == 0 + class FileObject: def __init__(self, file_name: str, directory: DirectoryObject): diff --git a/tests/unit/test_files.py b/tests/unit/test_files.py index 0093fea9..8b1864f1 100644 --- a/tests/unit/test_files.py +++ b/tests/unit/test_files.py @@ -45,6 +45,29 @@ def test_is_file(self): f.delete() self.assertFalse(f.is_file()) + def test_is_empty(self): + self.assertTrue(self.directory.is_empty()) + self.directory.write(file_name="test.txt", content="something") + self.assertFalse(self.directory.is_empty()) + + def test_delete(self): + self.assertTrue( + Path("test").exists() and Path("test").is_dir(), + msg="Sanity check on initial state" + ) + self.directory.write(file_name="test.txt", content="something") + self.directory.delete(only_if_empty=True) + self.assertFalse( + self.directory.is_empty(), + msg="Flag argument on delete should have prevented removal" + ) + self.directory.delete() + self.assertFalse( + Path("test").exists(), + msg="Delete should remove the entire directory" + ) + self.directory = DirectoryObject("test") # Rebuild it so the tearDown works + if __name__ == '__main__': unittest.main()