@@ -50,7 +50,19 @@ def resolve_resource_path(path: str | Path) -> Path:
50
50
return resolve (path )
51
51
52
52
53
- def resolve (path : str | Path ) -> Path :
53
+ def create_path (path : Path ) -> None :
54
+ """
55
+ Create a file or directory at the given path.
56
+ If the path has a suffix, it's treated as a file, otherwise, as a directory.
57
+ """
58
+ if path .suffix :
59
+ path .parent .mkdir (parents = True , exist_ok = True )
60
+ path .touch (exist_ok = True )
61
+ else :
62
+ path .mkdir (parents = True , exist_ok = True )
63
+
64
+
65
+ def resolve (path : str | Path , * , create : bool = False ) -> Path :
54
66
"""
55
67
Attempts to resolve a path to a resource including resource handles.
56
68
@@ -67,6 +79,7 @@ def resolve(path: str | Path) -> Path:
67
79
68
80
Args:
69
81
path: A Path or string
82
+ create: If True, create the path if it doesn't exist.
70
83
"""
71
84
# Convert to a Path object and resolve resource handle
72
85
if isinstance (path , str ):
@@ -87,22 +100,30 @@ def resolve(path: str | Path) -> Path:
87
100
# match. This allows for overriding of resources.
88
101
paths = get_resource_handle_paths (handle )
89
102
for handle_path in reversed (paths ):
90
- path = handle_path / resource
91
- if path .exists ():
103
+ candidate_path = handle_path / resource
104
+ if candidate_path .exists ():
105
+ path = candidate_path
92
106
break
93
107
else :
94
- searched_paths = "\n " .join (f"-> { p } " for p in reversed (paths ))
95
- raise FileNotFoundError (
96
- f"Cannot locate resource '{ resource } ' using handle "
97
- f"'{ handle } ' in any of the following paths:\n "
98
- f"{ searched_paths } "
99
- )
108
+ if create :
109
+ path = paths [- 1 ] / resource
110
+ create_path (path )
111
+ else :
112
+ searched_paths = "\n " .join (f"-> { p } " for p in reversed (paths ))
113
+ raise FileNotFoundError (
114
+ f"Cannot locate resource '{ resource } ' using handle "
115
+ f"'{ handle } ' in any of the following paths:\n "
116
+ f"{ searched_paths } "
117
+ )
100
118
101
119
# Always convert into a Path object
102
- path = Path (handle_path / resource )
120
+ path = Path (path )
103
121
else :
104
122
path = Path (path )
105
123
124
+ if create :
125
+ create_path (path )
126
+
106
127
try :
107
128
path = Path (path .resolve (strict = True ))
108
129
except AttributeError :
0 commit comments