Skip to content

Commit

Permalink
Merge pull request #17 from lappalainenj/del_if_exists
Browse files Browse the repository at this point in the history
del if exists flag
  • Loading branch information
lappalainenj authored Apr 22, 2024
2 parents 1f3881b + ac1fa73 commit 22fb185
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
12 changes: 12 additions & 0 deletions datamate/directory.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,8 +412,20 @@ def __new__(_type, *args: object, **kwargs: object) -> Any:
path, config = _parse_directory_args(args, kwargs)

if path is not None and isinstance(path, Path) and path.exists():
# case 1: path exists and global context is deleting if exists
if context.delete_if_exists:
shutil.rmtree(path)
# case 2: path exists and local kwargs are deleting if exists
if (
config is not None
and "delete_if_exists" in config
and config["delete_if_exists"]
):
shutil.rmtree(path)

if config is not None and "delete_if_exists" in config:
# always remove the deletion flag from the config
config.pop("delete_if_exists")

cls = _directory(_type)
_check_implementation(cls)
Expand Down
29 changes: 28 additions & 1 deletion tests/test_directory.py
Original file line number Diff line number Diff line change
Expand Up @@ -1133,7 +1133,7 @@ def test_delete_if_exists(tmp_path):
set_root_dir(tmp_path)

name = "test"
dir = DefaultConfigDir(name)
dir = DefaultConfigDir(name, x=2)
assert_directory_equals(
dir,
dict(
Expand Down Expand Up @@ -1163,3 +1163,30 @@ def test_delete_if_exists(tmp_path):
x=np.arange(3),
),
)

with pytest.raises(FileExistsError):
dir = DefaultConfigDir(name, x=2)

dir = DefaultConfigDir(name, x=2, delete_if_exists=True)
assert_directory_equals(
dir,
dict(
__type__=DefaultConfigDir,
__path__=tmp_path / name,
__conf__=Namespace(type="DefaultConfigDir", x=2),
__meta__={"config": {"type": "DefaultConfigDir", "x": 2}, "status": "done"},
x=np.arange(2),
),
)

dir = DefaultConfigDir(name, x=2, delete_if_exists=False)
assert_directory_equals(
dir,
dict(
__type__=DefaultConfigDir,
__path__=tmp_path / name,
__conf__=Namespace(type="DefaultConfigDir", x=2),
__meta__={"config": {"type": "DefaultConfigDir", "x": 2}, "status": "done"},
x=np.arange(2),
),
)

0 comments on commit 22fb185

Please sign in to comment.