Skip to content

Commit 969fc71

Browse files
committed
Add a parameter create to resolve() to create the directory/file if it doesn't exist.
1 parent 9c90129 commit 969fc71

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

arcade/resources/__init__.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def resolve_resource_path(path: str | Path) -> Path:
5050
return resolve(path)
5151

5252

53-
def resolve(path: str | Path) -> Path:
53+
def resolve(path: str | Path, *, create: bool = False) -> Path:
5454
"""
5555
Attempts to resolve a path to a resource including resource handles.
5656
@@ -67,6 +67,7 @@ def resolve(path: str | Path) -> Path:
6767
6868
Args:
6969
path: A Path or string
70+
create: If True, create the path if it doesn't exist.
7071
"""
7172
# Convert to a Path object and resolve resource handle
7273
if isinstance(path, str):
@@ -103,6 +104,15 @@ def resolve(path: str | Path) -> Path:
103104
else:
104105
path = Path(path)
105106

107+
if create:
108+
if path.suffix:
109+
# Path is a file so create a directory and file
110+
path.parent.mkdir(parents=True, exist_ok=True)
111+
path.touch(exist_ok=True)
112+
else:
113+
# Path is a directory so create it
114+
path.mkdir(parents=True, exist_ok=True)
115+
106116
try:
107117
path = Path(path.resolve(strict=True))
108118
except AttributeError:

tests/unit/resources/test_handles.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,22 @@ def test_default_handles():
1818
resources.resolve(":system:images/cards/cardBack_blue1.png")
1919

2020

21+
def test_handle_create(tmp_path):
22+
# Test directory creation
23+
new_dir = tmp_path / "created_dir"
24+
assert not new_dir.exists()
25+
result_dir = resources.resolve(new_dir, create=True)
26+
assert result_dir == new_dir.resolve()
27+
assert new_dir.exists() and new_dir.is_dir()
28+
29+
# Test file creation
30+
new_file = tmp_path / "created_file.txt"
31+
assert not new_file.exists()
32+
result_file = resources.resolve(new_file, create=True)
33+
assert result_file == new_file.resolve()
34+
assert new_file.exists() and new_file.is_file()
35+
36+
2137
def test_add_handles(monkeypatch):
2238
monkeypatch.setattr(resources, "handles", {})
2339

0 commit comments

Comments
 (0)