Only replace a const declaration at the start of the file
- ID
81a9818- date
2024-08-17 18:49:41+00:00- author
Alex Chan <alex@alexwlchan.net>- parent
54bb5f8- message
Only replace a `const` declaration at the start of the file- changed files
2 files, 6 additions, 2 deletions
Changed files
src/javascript/__init__.py (2393) → src/javascript/__init__.py (2413)
diff --git a/src/javascript/__init__.py b/src/javascript/__init__.py
index 9e41dd6..f37c2ea 100644
--- a/src/javascript/__init__.py
+++ b/src/javascript/__init__.py
@@ -1,6 +1,7 @@
import json
import os
import pathlib
+import re
import typing
@@ -24,12 +25,14 @@ def read_js(p: pathlib.Path | str, *, varname: str) -> typing.Any:
with open(p) as in_file:
contents = in_file.read()
- if not contents.startswith(f"const {varname} = "):
+ m = re.compile(r"^const %s = " % varname)
+
+ if not m.match(contents):
raise ValueError(
f"File {p} does not start with JavaScript `const` declaration!"
)
- json_string = contents.replace(f"const {varname} = ", "").rstrip().rstrip(";")
+ json_string = m.sub(repl="", string=contents).rstrip().rstrip(";")
return json.loads(json_string)
tests/test_javascript.py (4392) → tests/test_javascript.py (4431)
diff --git a/tests/test_javascript.py b/tests/test_javascript.py
index b704833..e6639a0 100644
--- a/tests/test_javascript.py
+++ b/tests/test_javascript.py
@@ -109,6 +109,7 @@ class TestRoundTrip:
{"colour": "red", "sides": 5},
'a string with "double quotes"',
"this is const myTestVariable",
+ "const myTestVariable = ",
],
)
def test_can_read_and_write_value(