Skip to content

Commit 6a47a82

Browse files
committed
add option to replace existing
1 parent a0c3740 commit 6a47a82

File tree

2 files changed

+29
-6
lines changed

2 files changed

+29
-6
lines changed

src/idom/web/module.py

+14-6
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,7 @@ def module_from_file(
176176
resolve_exports_depth: int = 5,
177177
symlink: bool = False,
178178
unmount_before_update: bool = False,
179+
replace_existing: bool = True,
179180
) -> WebModule:
180181
"""Load a :class:`WebModule` from a :data:`URL_SOURCE` using a known framework
181182
@@ -198,19 +199,26 @@ def module_from_file(
198199
only be used if the imported package failes to re-render when props change.
199200
Using this option has negative performance consequences since all DOM
200201
elements must be changed on each render. See :issue:`461` for more info.
202+
replace_existing:
203+
Whether to replace the source for a module with the same name if
204+
if already exists. Otherwise raise an error.
201205
"""
202206
source_file = Path(file)
203207
target_file = _web_module_path(name)
204208
if not source_file.exists():
205209
raise FileNotFoundError(f"Source file does not exist: {source_file}")
206210
elif target_file.exists() or target_file.is_symlink():
207-
raise FileExistsError(f"{name!r} already exists as {target_file.resolve()}")
208-
else:
209-
target_file.parent.mkdir(parents=True, exist_ok=True)
210-
if symlink:
211-
target_file.symlink_to(source_file)
211+
if not replace_existing:
212+
raise FileExistsError(f"{name!r} already exists as {target_file.resolve()}")
212213
else:
213-
shutil.copy(source_file, target_file)
214+
target_file.unlink()
215+
216+
target_file.parent.mkdir(parents=True, exist_ok=True)
217+
if symlink:
218+
target_file.symlink_to(source_file)
219+
else:
220+
shutil.copy(source_file, target_file)
221+
214222
return WebModule(
215223
source=name + module_name_suffix(name),
216224
source_type=NAME_SOURCE,

tests/test_web/test_module.py

+15
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,21 @@ def test_web_module_from_file_symlink(tmp_path):
143143
assert module.file.resolve().read_text() == "hello world!"
144144

145145

146+
def test_web_module_from_file_replace_existing(tmp_path):
147+
file1 = tmp_path / "temp1.js"
148+
file1.touch()
149+
150+
idom.web.module_from_file("temp", file1)
151+
152+
file2 = tmp_path / "temp2.js"
153+
file2.touch()
154+
155+
with pytest.raises(FileExistsError, match="already exists"):
156+
idom.web.module_from_file("temp", file2)
157+
158+
idom.web.module_from_file("temp", file2, replace_existing=True)
159+
160+
146161
def test_module_missing_exports():
147162
module = WebModule("test", NAME_SOURCE, None, {"a", "b", "c"}, None, False)
148163

0 commit comments

Comments
 (0)