Make append_to_js_array() more flexible about the file ending
- ID
6ff77d5- date
2024-08-17 20:08:49+00:00- author
Alex Chan <alex@alexwlchan.net>- parent
a023b4c- message
Make `append_to_js_array()` more flexible about the file ending- changed files
2 files, 44 additions, 2 deletions
Changed files
src/javascript/__init__.py (2423) → src/javascript/__init__.py (2984)
diff --git a/src/javascript/__init__.py b/src/javascript/__init__.py
index fbced59..b8ebdc4 100644
--- a/src/javascript/__init__.py
+++ b/src/javascript/__init__.py
@@ -83,5 +83,24 @@ def append_to_js_array(p: pathlib.Path | str, *, value: typing.Any) -> None:
if out_file.read(4) == b"\n];\n":
out_file.seek(file_size - 4)
out_file.write(json_to_append)
- else:
- raise ValueError(f"End of file {p!r} does not look like an array")
+ return
+
+ out_file.seek(file_size - 3)
+ if out_file.read(3) in {b"\n];", b"];\n"}:
+ out_file.seek(file_size - 3)
+ out_file.write(json_to_append)
+ return
+
+ out_file.seek(file_size - 2)
+ if out_file.read(2) in {b"];", b"]\n"}:
+ out_file.seek(file_size - 2)
+ out_file.write(json_to_append)
+ return
+
+ out_file.seek(file_size - 1)
+ if out_file.read(1) == b"]":
+ out_file.seek(file_size - 1)
+ out_file.write(json_to_append)
+ return
+
+ raise ValueError(f"End of file {p!r} does not look like an array")
tests/test_javascript.py (4509) → tests/test_javascript.py (5289)
diff --git a/tests/test_javascript.py b/tests/test_javascript.py
index c5fb33b..78418cb 100644
--- a/tests/test_javascript.py
+++ b/tests/test_javascript.py
@@ -78,6 +78,29 @@ class TestWriteJs:
class TestAppendToArray:
+ @pytest.mark.parametrize(
+ "text",
+ [
+ 'const fruit = ["apple", "banana", "coconut"];\n',
+ 'const fruit = ["apple","banana", "coconut"];',
+ 'const fruit = [\n "apple",\n "banana",\n "coconut"\n];\n',
+ 'const fruit = [\n "apple",\n "banana",\n "coconut"\n]',
+ 'const fruit = [\n "apple",\n "banana",\n "coconut"\n]',
+ ],
+ )
+ def test_can_append_array_value(self, tmp_path: pathlib.Path, text: str) -> None:
+ js_path = tmp_path / "food.js"
+
+ js_path.write_text(text)
+
+ append_to_js_array(js_path, value="damson")
+ assert read_js(js_path, varname="fruit") == [
+ "apple",
+ "banana",
+ "coconut",
+ "damson",
+ ]
+
def test_can_mix_types(self, tmp_path: pathlib.Path) -> None:
js_path = tmp_path / "food.js"