Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions pyiron_snippets/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def __init__(
self,
directory: str | Path | DirectoryObject = ".",
generate_unique_directory: bool | None = None,
protected: bool = False,
protected: bool | None = None,
):
"""
Initialize a DirectoryObject.
Expand All @@ -65,8 +65,9 @@ def __init__(
generate_unique_directory (bool | None): If True, generates a unique
directory name, otherwise it still generates a unique name if
the directory is "." and this parameter is None.
protected (bool): If True, prevents deletion of the directory object
on garbage collection.
protected (bool | None): If True, prevents deletion of the
directory object on garbage collection. If None, it defaults to
True if the directory already exists.
"""
if isinstance(directory, str):
path = Path(directory)
Expand All @@ -78,9 +79,11 @@ def __init__(
directory == "." and generate_unique_directory is None
) or generate_unique_directory:
path = path / f"data_{uuid.uuid4().hex}"
if protected is None:
protected = path.exists()
self._protected = protected
self.path: Path = path
self.create()
self._protected = protected

def __getstate__(self):
self._protected = True
Expand Down
10 changes: 10 additions & 0 deletions tests/unit/test_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,16 @@ def test_directory_instantiation(self):
self.assertTrue(str(directory.path).startswith("data"))
self.assertEqual(len(str(directory.path)), 37)

def test_protected(self):
directory = DirectoryObject("protected", protected=True)
self.assertTrue(directory._protected)
directory = DirectoryObject("protected")
self.assertTrue(directory._protected)
directory.delete()
directory = DirectoryObject("protected")
self.assertFalse(directory._protected)
directory.delete()

def test_directory_exists(self):
self.assertTrue(Path("test").exists() and Path("test").is_dir())

Expand Down
Loading