Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ The package version runs on its own semver; the schema it is generated from is `

## Unreleased

## 0.151.0 (2026-11-25)

### Changed

- **The three fixed names are read as written, and one held only in another case is refused.** `read_folder` lists the folder's root and reads `world.json`, `elements/` and `spatial/` exactly so: on a disk that ignores case it opened `Elements/` as `elements/`. A folder holding one of them only in another case now raises `FolderNameCaseError` (a `ValueError`, with `found` and `wanted`), never reads as a world with none; `misnamed_fixed_name(paths)` is the check. A world file holding them so is refused with the new reason `name_case` (`World.JSON` alone was `not_a_world`). Two names side by side stay `collision`. The `.owworld` fixture set's four new cases agree with this reader in their working copy; the package's tests replay them once the next schema serial vendors them.

## 0.150.2 (2026-11-25)

### Fixed
Expand Down
2 changes: 1 addition & 1 deletion src/onlyworlds/_version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.150.2"
__version__ = "0.151.0"
51 changes: 48 additions & 3 deletions src/onlyworlds/folder.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"DuplicateId",
"Folder",
"FolderElement",
"FolderNameCaseError",
"SkippedFile",
"WriteReport",
"element_filename",
Expand All @@ -54,6 +55,7 @@
"is_hidden",
"is_known_of",
"known_of_for_disk",
"misnamed_fixed_name",
"read_folder",
"resolve_filenames",
"slugify",
Expand Down Expand Up @@ -449,12 +451,50 @@ def _load_json(path: Path) -> Any:
return _outside_json.loads(text, parse_constant=_reject_constant)


_FIXED_NAMES: tuple[tuple[str, bool], ...] = (("world.json", False), ("elements", True), ("spatial", True))


def misnamed_fixed_name(paths: Iterable[str]) -> tuple[str, str] | None:
"""The first of the three fixed names (``world.json``, ``elements/``, ``spatial/``) that the paths
(relative, ``/``-separated) hold only in another case: the name as written and the name the
format wants, or None. A name held as written is never misnamed, whatever sits beside it. Names
fold as OW-18 folds them, NFC and then simple case folding at Unicode 15.1, so ``spatial/``
written with a long s (U+017F) first is ``spatial/`` in another case (folder spec 4.8)."""
from .worldfile import _fold_name # worldfile imports this module

firsts: dict[str, bool] = {}
for p in paths:
first, slash, _ = p.partition("/")
firsts[first] = firsts.get(first, False) or bool(slash)
for name, is_folder in _FIXED_NAMES:
if firsts.get(name) is is_folder:
continue
for first, folder in firsts.items():
if folder is is_folder and first != name and _fold_name(first) == name:
return (f"{first}/", f"{name}/") if is_folder else (first, name)
return None


class FolderNameCaseError(ValueError):
"""A world folder holds ``world.json``, ``elements/`` or ``spatial/`` only in another case:
refused with that cause, never read as a world with no elements (folder spec 4.8). ``found`` is
the name as written, ``wanted`` the name the format wants."""

def __init__(self, root: Path, found: str, wanted: str) -> None:
self.root, self.found, self.wanted = root, found, wanted
super().__init__(f"{root} holds {found} where the folder format names {wanted}: rename it {wanted}")


def read_folder(root: str | os.PathLike[str], *, legacy: bool = True) -> Folder:
"""Read a world folder. Opens files for reading only; the folder is never mutated.

- Every ``*.json`` in a type directory is ingested and keyed on its in-file ``id``;
the filename is never parsed (§3.1). A dot-prefixed file there is a tool's litter,
not an element: skipped and listed (clarified 2026-10-17).
- The three fixed names are read as written (from 0.151.0): ``world.json``, ``elements/`` and
``spatial/`` exactly so, by a listing of the root, so a disk that ignores case answers the same
as one that does not. A folder holding one of them only in another case (``Elements/`` and no
``elements/``) raises ``FolderNameCaseError`` naming it, never reads as a world with none.
- Names are read as written (ruled 2026-11-23): the extension is ``.json`` in lower case, so
``M.JSON`` is skipped and listed, and a type directory is the type word in lower case, so
``elements/Character/`` lands in ``ignored_dirs``. Two ids are the same id when they are
Expand All @@ -475,10 +515,14 @@ def read_folder(root: str | os.PathLike[str], *, legacy: bool = True) -> Folder:
and listed in ``Folder.known_of``; nothing is filled in for the fields it lacks.
"""
root = Path(root)
listed = {p.name: p.is_dir() for p in root.iterdir()} if root.is_dir() else {}
misnamed = misnamed_fixed_name(f"{n}/" if d else n for n, d in listed.items())
if misnamed:
raise FolderNameCaseError(root, *misnamed)
world_path = root / WORLD_FILE
world: dict[str, Any] | None = None
folder = Folder(root=root, world=None)
if world_path.is_file():
if listed.get(WORLD_FILE) is False:
try:
parsed = _load_json(world_path)
except (ValueError, UnicodeDecodeError) as exc:
Expand All @@ -497,8 +541,9 @@ def read_folder(root: str | os.PathLike[str], *, legacy: bool = True) -> Folder:
layouts.append(("spatial", LEGACY_SPATIAL_TYPES, folder.legacy))

for layout, allowed, sink in layouts:
base = root / (ELEMENTS_DIR if layout == "elements" else LEGACY_SPATIAL_DIR)
if not base.is_dir():
dir_name = ELEMENTS_DIR if layout == "elements" else LEGACY_SPATIAL_DIR
base = root / dir_name
if listed.get(dir_name) is not True: # as written: a disk that ignores case would open Elements/ here
continue
# By name in code point order (the format's one order), never by Path: a Windows path sorts
# case-blind, so a duplicate id would keep a different file there than on Linux or macOS.
Expand Down
17 changes: 16 additions & 1 deletion src/onlyworlds/worldfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@
from ._casefold import FOLD_RUNS
from ._jsonfmt import encode
from ._nfc import CLASS_RUNS, DECOMPOSITIONS, EXCLUSIONS
from .folder import ELEMENTS_DIR, LEGACY_SPATIAL_DIR, WORLD_FILE, is_hidden, read_folder, slugify
from .folder import ELEMENTS_DIR, LEGACY_SPATIAL_DIR, WORLD_FILE, is_hidden, misnamed_fixed_name, read_folder, slugify

__all__ = [
"MARKER_NAME",
Expand Down Expand Up @@ -120,6 +120,7 @@
"method",
"name",
"marker",
"name_case",
]

#: The spec's one list of causes (§4.7), as the TypeScript reader names them.
Expand All @@ -136,13 +137,15 @@
"method",
"name",
"marker",
"name_case",
)

_MESSAGES: Mapping[WorldFileReason, str] = {
"unsafe_path": "The world file holds a path that cannot be written safely.",
"too_big": "The world file is bigger than the budget allows, or a file in it is bigger than it says.",
"too_many": "The world file holds more files than the budget allows.",
"not_a_world": "The file is not a world: it has no readable world.json with an id.",
"name_case": "The world file holds world.json, elements/ or spatial/ in another case, and not the name itself.",
"more_than_one": "The file holds more than one world.",
"not_openable": "The file is not a zip that can be read.",
"duplicate": "The world file holds two entries with the same name.",
Expand Down Expand Up @@ -708,6 +711,13 @@ def read_world_file(
}
)
if not roots:
# A world.json in another case, at the root or in one top-level folder, is said as such (folder spec 4.8).
for n in sorted(candidates):
segs = n.split("/")
last = segs[-1]
at_top = len(segs) <= 2 and not segs[0].startswith(".")
if at_top and last != WORLD_FILE and _fold_name(last) == WORLD_FILE:
_refuse("name_case", f"It holds {n} where the folder format names {n[: -len(last)]}{WORLD_FILE}.")
_refuse("not_a_world", "There is no world.json at the root or in one top-level folder.")
if len(roots) > 1:
_refuse("more_than_one", f"The file holds worlds in {', '.join(roots)}.")
Expand All @@ -723,6 +733,11 @@ def read_world_file(
if rel != WORLD_FILE and rel.endswith(f"/{WORLD_FILE}") and not rel.startswith("records/"):
_refuse("more_than_one", f"A second world.json sits inside the world: {n}.")

# elements/ or spatial/ only in another case is refused, never read as a world with none (folder spec 4.8).
misnamed = misnamed_fixed_name(n[len(prefix) :] for n in inside)
if misnamed:
_refuse("name_case", f"It holds {prefix}{misnamed[0]} where the folder format names {prefix}{misnamed[1]}.")

# Every entry inflated within what it declares (OW-14), kept only when it is the world's.
content: dict[str, bytes] = {}
for e in files:
Expand Down
121 changes: 121 additions & 0 deletions tests/test_name_case.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
"""A fixed name held only in another case is refused with that cause (folder spec 4.8), never read as a
world with no elements; the three names are read as written; under spatial/ only the four are read."""

from __future__ import annotations

import io
import json
import zipfile
from pathlib import Path

import pytest

from onlyworlds.folder import FolderNameCaseError, misnamed_fixed_name, read_folder
from onlyworlds.worldfile import WorldFileError, read_world_file

WID = "0192a000-aaaa-7bbb-8ccc-000000000001"
CID = "0192a000-aaaa-7bbb-8ccc-0000000000c1"
LONG_S = chr(0x17F) + "patial"


def _world(root: Path, world_name: str = "world.json") -> None:
root.mkdir(parents=True, exist_ok=True)
(root / world_name).write_text(json.dumps({"id": WID, "name": "W"}, indent=2) + "\n", encoding="utf-8")


def _element(root: Path, rel: str, eid: str = CID) -> None:
p = root / rel
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(json.dumps({"id": eid, "name": "Ada"}, indent=2) + "\n", encoding="utf-8")


def _zip(files: dict[str, str]) -> bytes:
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
for name, text in files.items():
z.writestr(name, text)
return buf.getvalue()


W = json.dumps({"id": WID, "name": "W"})
E = json.dumps({"id": CID, "name": "Ada"})


@pytest.mark.parametrize(
("rel", "found", "wanted"),
[
("Elements/character/ada.json", "Elements/", "elements/"),
("Spatial/pin/p.json", "Spatial/", "spatial/"),
(f"{LONG_S}/pin/p.json", f"{LONG_S}/", "spatial/"),
],
)
def test_a_folder_holding_a_fixed_folder_only_in_another_case_raises(
tmp_path: Path, rel: str, found: str, wanted: str
) -> None:
_world(tmp_path)
_element(tmp_path, rel)
with pytest.raises(FolderNameCaseError) as exc:
read_folder(tmp_path)
assert (exc.value.found, exc.value.wanted) == (found, wanted)
assert f"holds {found} where the folder format names {wanted}" in str(exc.value)


def test_a_folder_holding_world_json_only_in_another_case_raises(tmp_path: Path) -> None:
_world(tmp_path, "World.JSON")
with pytest.raises(FolderNameCaseError, match=r"holds World\.JSON where the folder format names world\.json"):
read_folder(tmp_path)


def test_the_names_as_written_read_and_an_absent_folder_is_none(tmp_path: Path) -> None:
_world(tmp_path)
_element(tmp_path, "elements/character/ada.json")
f = read_folder(tmp_path)
assert f.world is not None and len(f.elements) == 1
bare = tmp_path / "bare"
_world(bare)
assert len(read_folder(bare).elements) == 0


def test_under_spatial_only_the_four_are_read_as_written(tmp_path: Path) -> None:
# Two folders: on a disk that ignores case, spatial/Pin/ and spatial/pin/ would be one directory.
odd = tmp_path / "odd"
_world(odd)
_element(odd, "spatial/character/a.json", "0192a000-aaaa-7bbb-8ccc-0000000000a1")
_element(odd, "spatial/Pin/p.json", "0192a000-aaaa-7bbb-8ccc-0000000000a2")
f = read_folder(odd)
assert f.legacy == {} and f.elements == {}
good = tmp_path / "good"
_world(good)
_element(good, "spatial/pin/q.json", "0192a000-aaaa-7bbb-8ccc-0000000000a3")
assert sorted(read_folder(good).legacy) == ["0192a000-aaaa-7bbb-8ccc-0000000000a3"]


@pytest.mark.parametrize(
"files",
[
{"w/world.json": W, "w/Elements/character/ada.json": E},
{"world.json": W, "ELEMENTS/character/ada.json": E},
{"w/world.json": W, f"w/{LONG_S}/pin/p.json": E},
{"World.JSON": W},
{"w/World.json": W},
],
)
def test_a_world_file_holding_a_fixed_name_only_in_another_case_is_name_case(files: dict[str, str]) -> None:
with pytest.raises(WorldFileError) as exc:
read_world_file(_zip(files))
assert exc.value.reason == "name_case"


def test_a_world_file_with_the_names_as_written_reads(tmp_path: Path) -> None:
assert len(read_world_file(_zip({"w/world.json": W, "w/elements/character/ada.json": E})).entries) == 2
assert len(read_world_file(_zip({"w/world.json": W, "w/notes/Elements.txt": "x"})).entries) == 2
with pytest.raises(WorldFileError) as exc:
read_world_file(_zip({".atlas/World.json": "{}"}))
assert exc.value.reason == "not_a_world"


def test_misnamed_fixed_name_reads_paths() -> None:
assert misnamed_fixed_name(["world.json", "Elements/x"]) == ("Elements/", "elements/")
assert misnamed_fixed_name(["world.json", "elements/x", "Elements/y"]) is None
assert misnamed_fixed_name(["world.json"]) is None
assert misnamed_fixed_name(["elements"]) is None # a file named elements is no folder
12 changes: 11 additions & 1 deletion tests/test_worldfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@
REPO = Path(__file__).resolve().parent.parent
SET_ROOT = Path(os.environ.get("OW_OWWORLD_FIXTURES") or REPO / "codegen" / "schema-dist" / "fixtures" / "owworld")
FIXTURES = SET_ROOT if (SET_ROOT / "verdicts.json").is_file() else SET_ROOT / "fixtures"
#: Causes the package names before the vendored set lists them, at the end of REASONS.
AHEAD_OF_THE_SET: tuple[str, ...] = ("name_case",)
CASE_FOLDING = REPO / "codegen" / "schema-dist" / "fixtures" / "owworld" / "CaseFolding-15.1.0.txt"
# Unicode's conformance file as published (unicode.org/Public/15.1.0/ucd/NormalizationTest.txt), byte for byte.
NORMALIZATION_TEST = REPO / "tests" / "fixtures" / "NormalizationTest-15.1.0.txt"
Expand Down Expand Up @@ -82,7 +84,15 @@ def tree(root: Path) -> dict[str, bytes]:
def test_the_owworld_fixture_set_every_verdict_and_every_cause(tmp_path: Path) -> None:
assert (FIXTURES / "verdicts.json").is_file(), f"no verdicts.json at {SET_ROOT} or under its fixtures/"
doc = json.loads((FIXTURES / "verdicts.json").read_text(encoding="utf-8"))
assert tuple(doc["reasons"]) == REASONS, "the set's causes are the package's, in the spec's order"
# The package may know a cause before the vendored set does (name_case, folder spec 4.8, until the serial that
# vendors its cases); once the set lists it, AHEAD_OF_THE_SET is emptied at that repin, or this goes red.
set_reasons = tuple(doc["reasons"])
if set_reasons == REASONS:
assert not AHEAD_OF_THE_SET or os.environ.get("OW_OWWORLD_FIXTURES"), (
f"the vendored set now lists {AHEAD_OF_THE_SET}: empty AHEAD_OF_THE_SET"
)
else:
assert set_reasons + AHEAD_OF_THE_SET == REASONS, "the set's causes are the package's, in the spec's order"
assert doc["floor"] == {"entries": WORLD_FILE_MAX_ENTRIES, "bytes": WORLD_FILE_MAX_BYTES}
assert doc["marker"] == WORLD_FILE_MEDIA_TYPE
on_disk = sorted(p.name for p in FIXTURES.iterdir() if p.suffix in (".owworld", ".zip"))
Expand Down
Loading