Skip to content

Create a unique folder when not specified by the user #55

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Aug 5, 2025
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
29 changes: 28 additions & 1 deletion pyiron_snippets/files.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import tarfile
import uuid
from pathlib import Path
from typing import cast

Expand Down Expand Up @@ -42,15 +43,41 @@ def categorize_folder_items(folder_path):


class DirectoryObject:
"""
A class to represent a directory object that can be created, deleted,
and managed. It can also compress and decompress its contents.
It supports unique directory generation and can be protected from deletion
on garbage collection.
"""

def __init__(
self, directory: str | Path | DirectoryObject, protected: bool = False
self,
directory: str | Path | DirectoryObject = ".",
generate_unique_directory: bool | None = None,
protected: bool = False,
):
"""
Initialize a DirectoryObject.

Args:
directory (str | Path | DirectoryObject): The directory path or
DirectoryObject instance.
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.
"""
if isinstance(directory, str):
path = Path(directory)
elif isinstance(directory, Path):
path = directory
elif isinstance(directory, DirectoryObject):
path = directory.path
if (
directory == "." and generate_unique_directory is None
) or generate_unique_directory:
path = path / f"data_{uuid.uuid4().hex}"
self.path: Path = path
self.create()
self._protected = protected
Expand Down
3 changes: 3 additions & 0 deletions tests/unit/test_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ def test_directory_instantiation(self):
self.assertEqual(directory.path, self.directory.path)
directory = DirectoryObject(self.directory)
self.assertEqual(directory.path, self.directory.path)
directory = DirectoryObject()
self.assertTrue(str(directory.path).startswith("data"))
self.assertEqual(len(str(directory.path)), 37)

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