diff --git a/CHANGELOG.md b/CHANGELOG.md index ad5911d..97b3d21 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ The package version runs on its own semver; the schema it is generated from is ` ## Unreleased +## 0.144.0 (2026-11-23) + +- **A share leaves out a file it could not read as an element.** `write_world_file(include_hidden=False)` and `world_file_bytes` carry a `.json` file in a type folder only when they read it as an element and found no hidden mark. A file there that could not be read is left out too, since its mark cannot be told: one that is not UTF-8 JSON (a write cut short), is nested more than 200 deep, holds a number that is not finite or an integer of more than 4,300 digits, or is not an object. Until now a share carried a file that was no JSON as it was, so a hidden element whose file was cut short travelled with its text. `unread_left_out=`, a second list the caller passes, receives those files' paths, sorted, apart from `hidden_left_out=`: a broken file is one a person may want to mend. This is the folder format's rule for a share, as ruled on 2026-11-23. +- **A copy carries such a file byte for byte, and no longer stops.** 0.143.0 raised `ValueError` on an element file nested too deep or holding a number it could not hold, in a share and in a copy that leaves author fields out. A copy is how a person moves their own world, broken file included: it now carries the file as it is, with whatever author fields it holds, and never rewrites it. Nothing raises for such a file any more. + ## 0.143.0 (2026-11-23) - **Fixed: `write_world_file(include_hidden=False)` could carry a hidden element.** 0.142.0 made the package's reader refuse a file nested more than 200 deep, and the writer of a world file took that refusal for "this file is no element": a hidden element whose file was nested that deep travelled in a share, whole and with its author fields, where 0.141.0 had left it out. The same was true in every earlier version for an element file holding an integer of more than 4,300 digits. Now a file the reader refuses stops the write: `write_world_file` and `world_file_bytes` raise `ValueError` naming the file and why, and nothing is written, whenever they would have had to read that file, to leave out the hidden (`include_hidden=False`) or to take out author fields (the default). A copy that leaves nothing out (`include_hidden=True, include_author_fields=True`) reads no element file and still carries every one byte for byte. Text that is no JSON at all is no element to any reader and travels as it is, as before. If you share world files from folders you did not write yourself, upgrade. diff --git a/README.md b/README.md index a15d514..9bae8e1 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ world = read_world_file("moppetopia.owworld") world.to_folder("moppetopia-copy") ``` -`write_world_file` carries `world.json` byte for byte (its `producer`, `source` and `format_version` included) and the folder's parts, `elements/`, `spatial/`, `media/` and `records/`, and nothing else: never an `api` block, never a tool's own folder unless you hand it in (`private_dir=".atlas"`, which makes the file a private copy rather than one to send around), and never a producer's records its `records/RECORDS.json` entry marks `"private": true` unless you ask (`include_private_records=True`); the manifest itself always travels as it is. A hidden element (`hidden: true` in its file) travels byte for byte, since the file is a copy; for a file you hand to someone else, `include_hidden=False` leaves every hidden element's file out whole, and a list passed as `hidden_left_out=` receives their paths. Nothing else changes, so a link from a visible element to a hidden one keeps an id the file no longer holds. An element's author fields (`created_by`, `changed_by`, `changed_via`, `changed_client` and `doors`) record which member and which tool wrote it, which means nothing to someone the world is handed to, so every element file leaves them out by default (`created_at` and `updated_at` stay): a file holding any of them is rewritten without them in the folder's own form, and a file holding none travels byte for byte. To archive your own world as it is on disk, pass `include_author_fields=True`. An element file the writer must read and cannot hold (nested more than 200 deep, or holding a number that is not finite or an integer of more than 4,300 digits) stops the write with a `ValueError` naming it: whether it is hidden cannot be told, and nothing is carried by guess. The same folder gives the same bytes on one Python. `read_world_file` checks the whole archive before it unpacks anything and refuses a file it cannot open safely with a `WorldFileError`, whose `reason` names one of the spec's twelve causes (`unsafe_path`, `collision`, `too_big`, ...). It gives the same verdict as the TypeScript and Unity SDKs on every case of the format's conformance set. +`write_world_file` carries `world.json` byte for byte (its `producer`, `source` and `format_version` included) and the folder's parts, `elements/`, `spatial/`, `media/` and `records/`, and nothing else: never an `api` block, never a tool's own folder unless you hand it in (`private_dir=".atlas"`, which makes the file a private copy rather than one to send around), and never a producer's records its `records/RECORDS.json` entry marks `"private": true` unless you ask (`include_private_records=True`); the manifest itself always travels as it is. A hidden element (`hidden: true` in its file) travels byte for byte, since the file is a copy; for a file you hand to someone else, `include_hidden=False` leaves every hidden element's file out whole, and a list passed as `hidden_left_out=` receives their paths. Nothing else changes, so a link from a visible element to a hidden one keeps an id the file no longer holds. An element's author fields (`created_by`, `changed_by`, `changed_via`, `changed_client` and `doors`) record which member and which tool wrote it, which means nothing to someone the world is handed to, so every element file leaves them out by default (`created_at` and `updated_at` stay): a file holding any of them is rewritten without them in the folder's own form, and a file holding none travels byte for byte. To archive your own world as it is on disk, pass `include_author_fields=True`. A share carries a file in a type folder only when it was read as an element and no mark was found: one that could not be read (not UTF-8 JSON, a write cut short, nested more than 200 deep, a number that is not finite, not an object) is left out as well, and a second list, `unread_left_out=`, receives those paths. A copy carries such a file byte for byte. The same folder gives the same bytes on one Python. `read_world_file` checks the whole archive before it unpacks anything and refuses a file it cannot open safely with a `WorldFileError`, whose `reason` names one of the spec's twelve causes (`unsafe_path`, `collision`, `too_big`, ...). It gives the same verdict as the TypeScript and Unity SDKs on every case of the format's conformance set. To send a folder's edits back, keep a copy exported before you edited, then push the difference: diff --git a/src/onlyworlds/_version.py b/src/onlyworlds/_version.py index 5a6bb17..3b5229b 100644 --- a/src/onlyworlds/_version.py +++ b/src/onlyworlds/_version.py @@ -1 +1 @@ -__version__ = "0.143.0" +__version__ = "0.144.0" diff --git a/src/onlyworlds/worldfile.py b/src/onlyworlds/worldfile.py index 8613002..2cb53ad 100644 --- a/src/onlyworlds/worldfile.py +++ b/src/onlyworlds/worldfile.py @@ -59,7 +59,6 @@ from __future__ import annotations import io -import json import os import re import shutil @@ -836,35 +835,28 @@ def _default_top(world: Mapping[str, Any]) -> str: return f"{slugify(name if isinstance(name, str) else None) or 'world'}-{str(world['id'])[:8]}" -def _element_body(rel: str, src: Path, to: str) -> Any: +class _Unread: + """An element file the writer could not read as an element.""" + + +_UNREAD = _Unread() + + +def _element_body(rel: str, src: Path) -> dict[str, Any] | _Unread | None: """What an element file holds (a ``.json`` file directly in a type folder of ``elements/`` or legacy - ``spatial/``), for a writer that must read it ``to`` leave something out. None for a file anywhere else, - or one that is not UTF-8 JSON: no reader takes that as an element, and it is carried as it is, as ever. + ``spatial/``): its JSON object. None for a file anywhere else, which is no element file. - A file that is JSON this package's reader refuses (nested past its depth, a number it cannot hold) raises - ``ValueError``: what it holds cannot be read, so the writer leaves nothing in by guess, as with a records - manifest it cannot read (OW-8).""" + ``_UNREAD`` for a file there that could not be read as an element: not UTF-8, not JSON (a write cut + short), JSON this package's reader refuses (nested past its depth, a number it cannot hold), or not an + object. What such a file holds cannot be told, its hidden mark included.""" segs = rel.split("/") if len(segs) != 3 or segs[0] not in (ELEMENTS_DIR, LEGACY_SPATIAL_DIR) or not rel.lower().endswith(".json"): return None try: - return _outside_json.loads(src.read_bytes().decode("utf-8-sig")) - except (UnicodeDecodeError, json.JSONDecodeError): - return None - except ValueError as exc: - raise ValueError( - f"{src} cannot be read ({exc}), so the writer cannot {to} and carries nothing by guess. Fix or " - "remove the file, or pass include_hidden=True and include_author_fields=True to carry every file " - "as it is." - ) from None - - -def _hidden_element_file(rel: str, src: Path) -> bool: - """An element file whose JSON object carries the hidden mark at the top level (``folder.is_hidden``). - A file that is not an element file, or not a JSON object, is carried as it is, as ever; one the reader - refuses raises (``_element_body``).""" - body = _element_body(rel, src, "tell whether it is hidden") - return isinstance(body, dict) and is_hidden(body) + body = _outside_json.loads(src.read_bytes().decode("utf-8-sig")) + except ValueError: # not UTF-8, not JSON, or JSON the reader refuses + return _UNREAD + return body if isinstance(body, dict) else _UNREAD #: Which member and which tool wrote an element (a membership id, a door): nothing to someone the @@ -876,10 +868,9 @@ def _without_author_fields(rel: str, src: Path) -> bytes | None: """An element file (``.json`` directly in a type folder of ``elements/`` or legacy ``spatial/``, as the TypeScript writer reads one) without its author fields, in the folder's own form (``_jsonfmt.encode``: two-space indent, a trailing newline, the other keys in their order), or - None when it holds none of them or is not a JSON object: then it travels byte for byte. Only - top-level keys go; an ``x_*`` value that holds one of the names is the extension's, and stays. - A file the reader refuses raises (``_element_body``): its author fields cannot be told from its bytes.""" - body = _element_body(rel, src, "take out its author fields") + None when it holds none of them or could not be read as an element: then it travels byte for byte. + Only top-level keys go; an ``x_*`` value that holds one of the names is the extension's, and stays.""" + body = _element_body(rel, src) if not isinstance(body, dict) or not any(k in body for k in _AUTHOR_FIELDS): return None return encode({k: v for k, v in body.items() if k not in _AUTHOR_FIELDS}) @@ -893,6 +884,7 @@ def _plan( include_hidden: bool = True, hidden_left_out: list[str] | None = None, include_author_fields: bool = False, + unread_left_out: list[str] | None = None, ) -> tuple[str, list[tuple[str, Path | bytes]]]: root = Path(folder) if not root.is_dir(): @@ -916,11 +908,23 @@ def in_private(rel: str) -> bool: files = {rel: src for rel, src in files.items() if not in_private(rel)} if not include_hidden: - # A share (§4.8): each hidden element's file left out whole; nothing else rewritten. - hidden = sorted(rel for rel, src in files.items() if _hidden_element_file(rel, src)) - files = {rel: src for rel, src in files.items() if rel not in set(hidden)} + # A share (§4.8): it carries an element file only when it was read as an element and no mark was + # found. A hidden element's file is left out whole, and so is one that could not be read, listed + # apart; nothing else is rewritten. + hidden: list[str] = [] + unread: list[str] = [] + for rel in sorted(files): + body = _element_body(rel, files[rel]) + if isinstance(body, _Unread): + unread.append(rel) + elif body is not None and is_hidden(body): + hidden.append(rel) + left = {*hidden, *unread} + files = {rel: src for rel, src in files.items() if rel not in left} if hidden_left_out is not None: hidden_left_out.extend(hidden) + if unread_left_out is not None: + unread_left_out.extend(unread) raw = files[WORLD_FILE].read_bytes() world_bytes, world = _without_link(raw, _parse_world(raw)) top = _default_top(world) if top_dir is None else top_dir @@ -983,13 +987,21 @@ def world_file_bytes( include_hidden: bool = True, hidden_left_out: list[str] | None = None, include_author_fields: bool = False, + unread_left_out: list[str] | None = None, ) -> bytes: """The world file for the folder at ``folder``, as bytes. See ``write_world_file``: the same keywords, the same refusals, private records left out unless ``include_private_records=True``, hidden elements kept unless ``include_hidden=False``, author fields left out unless ``include_author_fields=True``.""" top, plan = _plan( - folder, top_dir, private_dir, include_private_records, include_hidden, hidden_left_out, include_author_fields + folder, + top_dir, + private_dir, + include_private_records, + include_hidden, + hidden_left_out, + include_author_fields, + unread_left_out, ) buf = io.BytesIO() _write(buf, top, plan) @@ -1006,6 +1018,7 @@ def write_world_file( include_hidden: bool = True, hidden_left_out: list[str] | None = None, include_author_fields: bool = False, + unread_left_out: list[str] | None = None, ) -> Path: """Write the folder at ``folder`` as one world file at ``path``; returns ``path``. @@ -1035,7 +1048,12 @@ def write_world_file( passes, receives each left-out file's path inside the folder (``elements/character/x.json``), sorted, and its length is the count. Nothing else is rewritten: a visible element that links to a hidden one keeps the id, which dangles in the file (a reader meets it as a link to an - element the world does not hold). + element the world does not hold). A share carries a file in a type folder only when it + was read as an element and no mark was found: one that could not be read (not UTF-8 JSON, a + write cut short, nested more than 200 deep, a number that is not finite, not an object) is + left out too, since its mark cannot be told, and ``unread_left_out``, a second list the + caller passes, receives those paths, sorted. They are counted apart: a broken file is one a + person may want to mend. A copy carries such a file byte for byte. - Author fields are left out: ``created_by``, ``changed_by``, ``changed_via``, ``changed_client`` and ``doors`` record which member and which tool wrote each element (a membership id, a door), which means nothing to someone the world is handed to, so every @@ -1062,7 +1080,14 @@ def write_world_file( a crash never leaves half a file. """ top, plan = _plan( - folder, top_dir, private_dir, include_private_records, include_hidden, hidden_left_out, include_author_fields + folder, + top_dir, + private_dir, + include_private_records, + include_hidden, + hidden_left_out, + include_author_fields, + unread_left_out, ) target = Path(path) tmp = target.parent / f".{target.name}.tmp-{uuid.uuid4().hex[:8]}" diff --git a/tests/test_outside_json.py b/tests/test_outside_json.py index e546f8a..608cfbb 100644 --- a/tests/test_outside_json.py +++ b/tests/test_outside_json.py @@ -1,9 +1,9 @@ """Text this package did not write (a folder's file, an archive, another tool's export) is parsed through ``_outside_json.loads``: JSON it cannot hold as written (nested past its depth, an integer past Python's digit limit, a number that is not finite) must come back as a ``ValueError`` a reader catches, never a -traceback and never a value the file does not hold. A writer that must read a file to leave something out -refuses to write when the reader refuses the file. And every ``json.loads`` in the package is either that -one or named here.""" +traceback and never a value the file does not hold. The world file's writer leaves a file it could not read +as an element out of a share, listed apart from the hidden, and carries it byte for byte in a copy. And every +``json.loads`` in the package is either that one or named here.""" from __future__ import annotations @@ -17,7 +17,7 @@ from onlyworlds import _outside_json, read_folder, write_folder from onlyworlds.folder import FORMAT_VERSION from onlyworlds.kanka import import_kanka -from onlyworlds.worldfile import read_world_file, world_file_bytes, write_world_file +from onlyworlds.worldfile import read_world_file, world_file_bytes SRC = Path(__file__).resolve().parent.parent / "src" / "onlyworlds" DEEP = "[" * 100_000 + "]" * 100_000 @@ -132,7 +132,7 @@ def calls(path: Path, module: str) -> int: # --- a writer that must read a file to leave something out ------------------------------------------------ -#: What stands where a key's value goes in a hidden element's file, and whether the reader holds the file. +#: What stands where a key's value goes in a hidden element's file that the reader does not hold. REFUSED = { "nested 201 deep": "[" * 200 + "]" * 200, "nested 100,000 deep": DEEP, @@ -153,32 +153,50 @@ def _folder_with_hidden(root: Path, planted: str) -> tuple[Path, bytes]: @pytest.mark.parametrize("planted", REFUSED.values(), ids=REFUSED.keys()) -def test_a_share_is_refused_when_a_file_it_must_read_cannot_be_held(tmp_path: Path, planted: str) -> None: +def test_a_share_leaves_out_a_file_it_could_not_read_and_a_copy_carries_it(tmp_path: Path, planted: str) -> None: """0.142.0 carried such a hidden element into a share with its author fields: the reader refused the file, - and the writer took the refusal for "not an element".""" + and the writer took the refusal for "not an element". 0.143.0 refused the write. As ruled since: a share + carries a file in a type folder only when it was read as an element and no mark was found.""" secret, data = _folder_with_hidden(tmp_path / "w", planted) - out = tmp_path / "share.owworld" - # A share, a plain copy (author fields left out by default), and the hidden mark alone. - for hidden, authors in ((False, False), (True, False), (False, True)): - with pytest.raises(ValueError, match="carries nothing by guess") as err: - write_world_file(tmp_path / "w", out, include_hidden=hidden, include_author_fields=authors) - assert not isinstance(err.value, json.JSONDecodeError) - assert str(secret) in str(err.value) and not out.exists() - # A copy that leaves nothing out reads nothing, and carries the file byte for byte. - whole = read_world_file(world_file_bytes(tmp_path / "w", include_author_fields=True)).entries - assert whole["elements/character/cy--c-2.json"] == data - - -def test_a_share_leaves_out_a_hidden_element_at_the_depth_line_and_carries_text_that_is_no_json(tmp_path: Path) -> None: + rel = "elements/character/cy--c-2.json" + hidden: list[str] = [] + unread: list[str] = [] + share = read_world_file( + world_file_bytes(tmp_path / "w", include_hidden=False, hidden_left_out=hidden, unread_left_out=unread) + ).entries + assert rel not in share + assert (hidden, unread) == ([], [rel]), "listed apart from the hidden" + # A copy carries it byte for byte, with author fields left out of the others (the default) or not. + for authors in (False, True): + whole = read_world_file(world_file_bytes(tmp_path / "w", include_author_fields=authors)).entries + assert whole[rel] == data + assert secret.read_bytes() == data + + +def test_a_share_at_the_depth_line_and_on_text_that_is_no_json(tmp_path: Path) -> None: secret, _ = _folder_with_hidden(tmp_path / "w", "[" * 199 + "]" * 199) - left: list[str] = [] - share = read_world_file(world_file_bytes(tmp_path / "w", include_hidden=False, hidden_left_out=left)).entries - assert left == ["elements/character/cy--c-2.json"] and "elements/character/cy--c-2.json" not in share - # Text that is no JSON is no element to any reader: carried as it is, as ever. - secret.write_bytes(b'{"id": "c-2", "hidden": true, ') - left = [] - share = read_world_file(world_file_bytes(tmp_path / "w", include_hidden=False, hidden_left_out=left)).entries - assert left == [] and share["elements/character/cy--c-2.json"] == b'{"id": "c-2", "hidden": true, ' + rel = "elements/character/cy--c-2.json" + hidden: list[str] = [] + unread: list[str] = [] + share = read_world_file( + world_file_bytes(tmp_path / "w", include_hidden=False, hidden_left_out=hidden, unread_left_out=unread) + ).entries + assert (hidden, unread) == ([rel], []) and rel not in share, "read at the line: hidden, left out as hidden" + # A hidden element's file cut short: no JSON, so its mark cannot be told. Left out of a share, carried by a copy. + cut = b'{"id": "c-2", "hidden": true, ' + secret.write_bytes(cut) + for broken in (cut, b"[1, 2]", b'{"\xe9":1}'): + secret.write_bytes(broken) + hidden, unread = [], [] + share = read_world_file( + world_file_bytes(tmp_path / "w", include_hidden=False, hidden_left_out=hidden, unread_left_out=unread) + ).entries + assert (hidden, unread) == ([], [rel]) and rel not in share + assert read_world_file(world_file_bytes(tmp_path / "w")).entries[rel] == broken + # Without the lists the same bytes are written. + assert world_file_bytes(tmp_path / "w", include_hidden=False) == world_file_bytes( + tmp_path / "w", include_hidden=False, unread_left_out=[] + ) # --- the Kanka door ---------------------------------------------------------------------------------------- diff --git a/tests/test_worldfile.py b/tests/test_worldfile.py index 95875ff..e2902df 100644 --- a/tests/test_worldfile.py +++ b/tests/test_worldfile.py @@ -590,23 +590,28 @@ def test_a_hidden_element_travels_byte_for_byte_unless_the_file_is_a_share(tmp_p "elements/character/cy--c-2.json": secret, "elements/character/dee--c-3.json": encode({"id": "c-3", "name": "Dee", "hidden": False}), "spatial/pin/p--p-1.json": encode({"id": "p-1", "name": "P", "hidden": True}), - "elements/character/notes.json": b"[1, 2]", # not an element object: carried as ever + "elements/character/notes.json": b"[1, 2]", # not an element object: a copy carries it, a share cannot read it "media/hidden.json": encode({"hidden": True}), # not an element file } src = make_folder(tmp_path / "w", files) kept = read_world_file(world_file_bytes(src)).entries assert kept["elements/character/cy--c-2.json"] == secret and len(kept) == len(files) left: list[str] = [] - share = world_file_bytes(src, include_hidden=False, hidden_left_out=left) + unread: list[str] = [] + share = world_file_bytes(src, include_hidden=False, hidden_left_out=left, unread_left_out=unread) assert left == ["elements/character/cy--c-2.json", "spatial/pin/p--p-1.json"] + assert unread == ["elements/character/notes.json"] # listed apart from the hidden (since 0.144.0; carried before) entries = read_world_file(share).entries - assert set(kept) - set(entries) == set(left) + assert set(kept) - set(entries) == {*left, *unread} assert all(entries[p] == kept[p] for p in entries), "nothing else rewritten" assert b'"c-2"' in entries["elements/character/ann--c-1.json"] # the link id dangles, as ruled assert world_file_bytes(src, include_hidden=False) == share and world_file_bytes(src) == world_file_bytes(src) again: list[str] = [] - written = write_world_file(src, tmp_path / "share.owworld", include_hidden=False, hidden_left_out=again) - assert written.read_bytes() == share and again == left + again_unread: list[str] = [] + written = write_world_file( + src, tmp_path / "share.owworld", include_hidden=False, hidden_left_out=again, unread_left_out=again_unread + ) + assert written.read_bytes() == share and again == left and again_unread == unread def test_only_a_file_directly_in_a_type_folder_is_an_element_for_the_hidden_mark(tmp_path: Path) -> None: @@ -704,15 +709,19 @@ def test_author_fields_a_share_and_a_tools_dot_folder(tmp_path: Path) -> None: }, ) left: list[str] = [] - share = world_file_bytes(src, private_dir=".atlas", include_hidden=False, hidden_left_out=left) + unread: list[str] = [] + share = world_file_bytes( + src, private_dir=".atlas", include_hidden=False, hidden_left_out=left, unread_left_out=unread + ) out = read_world_file(share).entries assert left == ["elements/character/ada.json"] + assert unread == ["elements/character/latin.json"] # not UTF-8: its mark cannot be told assert list(out) == [ ".atlas/elements/character/c.json", "elements/character/bo.json", - "elements/character/latin.json", "world.json", ] + copy = read_world_file(world_file_bytes(src, private_dir=".atlas")).entries + assert copy["elements/character/latin.json"] == b'{"\xe9":1}' # a copy carries it byte for byte assert out["elements/character/bo.json"] == encode({"id": "b"}) assert out[".atlas/elements/character/c.json"] == encode({"id": "c", "created_by": "u"}) - assert out["elements/character/latin.json"] == b'{"\xe9":1}', "not UTF-8: travels as it is"