diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index f68d997..9d20ae1 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -21,7 +21,7 @@ jobs: uses: actions/checkout@v7 with: repository: EVEShipFit/esf-format - ref: v1.2 + ref: load-document path: esf-format - name: Install uv diff --git a/README.md b/README.md index f19dff1..f1851a2 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,34 @@ Catch a subclass to handle one kind of error: | `EsfCatalogError` | The catalog does not know a name or ID, or a name matches more than one type. | | `EsfRuleError` | The fit breaks a rule, like a module in the wrong rack. | +## Other data in a document + +A document can hold more than fits. Other formats, like a fleet, add their own +text blocks, such as `%fleet/1`, or their own binary fields. `load()` skips +them. `load_document()` reads the fits the same way, and also hands back what +it skipped: + +```python +doc = esf_format.load_document(data, catalog) +doc.fits # the same as load() +for extra in doc.extra: # in document order + if isinstance(extra, esf_format.TextExtra): + extra.name, extra.version, extra.text # "fleet", 1, the lines after "%fleet/1" + else: # esf_format.BinaryExtra + extra.field, extra.bytes # a binary field number, 2 or more, and its content +``` + +`text` is the block exactly as written, after its header line. Of the binary +fields, only length-delimited ones come back. + +To store data next to fits, add it to the end of what `save()` or +`save_binary()` returns. Two documents joined are one document: + +```python +text = esf_format.save(fits, catalog) + "%fleet/1\n" + fleet_text +data = esf_format.save_binary(fits, catalog) + esf_format.binary_field(2, fleet_bytes) +``` + ## Fits An `EsfFit` is one fit: `hull`, `name`, tactical `mode` and its `entries`. @@ -142,7 +170,7 @@ you use a type as one. The test cases live in [esf-format](https://github.com/EVEShipFit/esf-format): ``` -git clone --branch v1.0 https://github.com/EVEShipFit/esf-format +git clone --branch load-document https://github.com/EVEShipFit/esf-format uv sync uv run --project esf-format/tools esf-test -- .venv/bin/python tests/program.py uv run pytest diff --git a/src/esf_format/__init__.py b/src/esf_format/__init__.py index 2128243..8800207 100644 --- a/src/esf_format/__init__.py +++ b/src/esf_format/__init__.py @@ -3,7 +3,7 @@ import base64 import re -from . import binary, canonical, esi, resolve, sde, source, text +from . import binary, canonical, esi, resolve, sde, source, text, wire from .canonical import CanonFit from .catalog import ( AttributeRecord, @@ -15,30 +15,36 @@ TypeRecord, ) from .errors import EsfCatalogError, EsfError, EsfFormatError, EsfRuleError -from .model import Entry, EsfFit, Location, State +from .model import BinaryExtra, Document, Entry, EsfFit, Extra, Location, State, TextExtra from .names import fold __all__ = [ "AttributeRecord", + "BinaryExtra", "Catalog", + "Document", "Entry", "EsfCatalogError", "EsfError", "EsfFit", "EsfFormatError", "EsfRuleError", + "Extra", "Kind", "Location", "ModeCatalog", "MutaplasmidCatalog", "MutaplasmidRecord", "State", + "TextExtra", "TypeRecord", + "binary_field", "esi", "fold", "from_base64url", "is_text", "load", + "load_document", "save", "save_binary", "sde", @@ -65,7 +71,7 @@ def _canonical( def _checked(fits: list[EsfFit], catalog: Catalog) -> list[CanonFit]: data, where = source.source(fits, catalog) try: - return _canonical(text.parse(data), catalog, fits) + return _canonical(text.parse(data)[0], catalog, fits) except EsfError as e: if e.line is None: raise @@ -73,17 +79,38 @@ def _checked(fits: list[EsfFit], catalog: Catalog) -> list[CanonFit]: raise e._at(fit, entry) from None -def load(data: bytes | str, catalog: Catalog) -> list[EsfFit]: - """Read a text or binary document, in canonical form.""" +def _load(data: bytes | str, catalog: Catalog, keep: bool) -> Document: if isinstance(data, str): data = data.encode("utf-8", "surrogatepass") if not data: raise EsfFormatError("the document is empty") + extra: list[Extra] = [] if is_text(data): - fits = _canonical(text.parse(data), catalog) + blocks, text_extra = text.parse(data, keep) + fits = _canonical(blocks, catalog) + extra += text_extra else: - fits = _checked(binary.decode(data), catalog) - return [canonical.to_model(f) for f in fits] + decoded, binary_extra = binary.decode(data) + fits = _checked(decoded, catalog) + extra += binary_extra + return Document([canonical.to_model(f) for f in fits], extra) + + +def load(data: bytes | str, catalog: Catalog) -> list[EsfFit]: + """Read a text or binary document, in canonical form.""" + return _load(data, catalog, False).fits + + +def load_document(data: bytes | str, catalog: Catalog) -> Document: + """Read a text or binary document, and keep what is not a fit. + + The fits are the same as `load()` returns. A reader skips text blocks and binary + `Document` fields that are not fits; this hands them back in `Document.extra`, in + the order of the document. Of the binary fields, only length-delimited ones come + back. It raises the same errors as `load()`, and one more: a text block whose + version is above 4294967295 raises `EsfFormatError`, where `load()` skips it. + """ + return _load(data, catalog, True) def save(fits: list[EsfFit], catalog: Catalog) -> str: @@ -96,6 +123,19 @@ def save_binary(fits: list[EsfFit], catalog: Catalog) -> bytes: return binary.encode([canonical.to_model(f) for f in _checked(fits, catalog)]) +def binary_field(field: int, data: bytes) -> bytes: + """A length-delimited `Document` field, to append to the output of `save_binary()`. + + Two binary documents joined are one document, so adding this to the end of + `save_binary()` output stores `data` next to the fits. `load_document()` hands it + back as a `BinaryExtra`. `field` is the field number: 2 or more, as 1 holds the + fits, and at most 536870911. Anything else raises ValueError. + """ + if not 2 <= field <= wire.MAX_FIELD: + raise ValueError(f"field must be from 2 to {wire.MAX_FIELD}, not {field}") + return wire.record(field, bytes(memoryview(data))) + + def to_base64url(data: bytes) -> str: """The binary form as base64url without padding, for URLs (§10.4).""" return base64.urlsafe_b64encode(data).rstrip(b"=").decode() diff --git a/src/esf_format/binary.py b/src/esf_format/binary.py index bb94a0a..8050f78 100644 --- a/src/esf_format/binary.py +++ b/src/esf_format/binary.py @@ -4,7 +4,7 @@ from typing import TypeVar from . import wire -from .model import Entry, EsfFit, Location, State +from .model import BinaryExtra, Entry, EsfFit, Location, State T = TypeVar("T") from .errors import EsfFormatError, EsfRuleError @@ -173,14 +173,17 @@ def _decode_fit(data: bytes) -> EsfFit: return fit -def decode(data: bytes) -> list[EsfFit]: +def decode(data: bytes) -> tuple[list[EsfFit], list[BinaryExtra]]: fits = [] + extras = [] for tag, wire_type, value in wire.fields(data): if tag != 1: + if wire_type == wire.LEN: + extras.append(BinaryExtra(tag, value)) continue if wire_type != wire.LEN: raise EsfFormatError("binary: Document.fits has the wrong wire type") fits.append(_decode_fit(value)) if not fits: raise EsfFormatError("binary: a document holds at least one fit") - return fits + return fits, extras diff --git a/src/esf_format/model.py b/src/esf_format/model.py index 2afcd76..c7c2198 100644 --- a/src/esf_format/model.py +++ b/src/esf_format/model.py @@ -229,3 +229,57 @@ class EsfFit: entries: list[Entry] = field(default_factory=list) """The lines of the fit: items, empty slots and fits it carries.""" + + +@dataclass +class TextExtra: + """A text block that is not a fit, like a `%fleet/1` block. + + A reader skips such a block (esf/1 spec §6.11). `load_document()` hands it back. + """ + + name: str + """The name in the block's header, like "fleet" for `%fleet/1`.""" + + version: int + """The version in the block's header, like 1 for `%fleet/1`. + + It is at most 4294967295; `load_document()` rejects a block with a larger one. + """ + + text: str + """The block as written, after its header line, up to the next header or the end. + + It keeps the line endings, CRLF or LF, and any blank lines at the end. It is empty + when nothing follows the header line before the next header or the end. + """ + + +@dataclass +class BinaryExtra: + """A field of a binary document that is not a fit. + + A reader skips a `Document` field it does not know (esf/1 spec §10.2). + `load_document()` hands back the length-delimited ones (wire type 2). + """ + + field: int + """The field number, 2 or more.""" + + bytes: bytes + """The field's content, without its key and length.""" + + +Extra = TextExtra | BinaryExtra +"""Data in a document that is not a fit.""" + + +@dataclass +class Document: + """A document as `load_document()` reads it: its fits, and everything else.""" + + fits: list[EsfFit] + """The fits, in canonical form, the same as `load()` returns.""" + + extra: list[Extra] = field(default_factory=list) + """The blocks or binary fields that are not fits, in the order of the document.""" diff --git a/src/esf_format/text.py b/src/esf_format/text.py index c1ae4ae..378857a 100644 --- a/src/esf_format/text.py +++ b/src/esf_format/text.py @@ -5,6 +5,7 @@ from typing import NamedTuple, NoReturn from .errors import EsfFormatError +from .model import TextExtra SIGILS = frozenset(':+{!@/"') RACKS = ("sub", "high", "mid", "low", "rig", "svc") @@ -334,8 +335,8 @@ def _is_blank(text: str) -> bool: return stripped == "" or stripped.startswith("//") -def parse(data: bytes) -> list[FitBlock]: - """Split a text document into fits; other blocks are skipped.""" +def parse(data: bytes, keep: bool = False) -> tuple[list[FitBlock], list[TextExtra]]: + """Split a text document into fits, and the other blocks if `keep`.""" try: text = data.decode("utf-8") except UnicodeDecodeError as e: @@ -346,10 +347,14 @@ def parse(data: bytes) -> list[FitBlock]: lines.pop() fits: list[FitBlock] = [] + extras: list[TextExtra] = [] + extra_start: int | None = None + start = 0 current: FitBlock | None = None header: int | None = None # an esf header still waiting for its hull line in_block = False for number, raw in enumerate(lines, 1): + line_start, start = start, start + len(raw) + 1 raw = raw.removesuffix("\r") if "\r" in raw: raise EsfFormatError("a CR must be followed by an LF", number) @@ -360,12 +365,21 @@ def parse(data: bytes) -> list[FitBlock]: raise EsfFormatError("malformed header", number) if header is not None: raise EsfFormatError("a fit needs a hull line", header) + if extra_start is not None: + extras[-1].text = text[extra_start:line_start] in_block = True current = None + extra_start = None if match.group(1) == "esf": if match.group(2) != "1": raise EsfFormatError(f"unsupported version esf/{match.group(2)}", number) header = number + elif keep: + version = match.group(2).lstrip("0") or "0" + if len(version) > 10 or int(version) > UINT32_MAX: + raise EsfFormatError("a block version is too large", number) + extras.append(TextExtra(match.group(1), int(version), "")) + extra_start = min(start, len(text)) continue if not in_block: @@ -385,4 +399,6 @@ def parse(data: bytes) -> list[FitBlock]: raise EsfFormatError("a fit needs a hull line", header) if not fits: raise EsfFormatError("a document holds at least one fit") - return fits + if extra_start is not None: + extras[-1].text = text[extra_start:] + return fits, extras diff --git a/src/esf_format/wire.py b/src/esf_format/wire.py index 1513559..51988d2 100644 --- a/src/esf_format/wire.py +++ b/src/esf_format/wire.py @@ -8,6 +8,7 @@ VARINT, I64, LEN, SGROUP, EGROUP, I32 = range(6) U64 = (1 << 64) - 1 +MAX_FIELD = (1 << 29) - 1 def varint(value: int) -> bytes: diff --git a/tests/program.py b/tests/program.py index d8c4751..8233dcc 100644 --- a/tests/program.py +++ b/tests/program.py @@ -1,5 +1,6 @@ -"""The program the esf-format test runner calls: program.py check|canonical|binary.""" +"""The program the esf-format test runner calls: program.py check|canonical|binary|extra.""" +import json import os import sys @@ -12,7 +13,16 @@ def main() -> int: command = sys.argv[1] catalog = JsonCatalog(os.environ["ESF_CATALOG"]) try: - fits = esf_format.load(sys.stdin.buffer.read(), catalog) + data = sys.stdin.buffer.read() + if command == "extra": + for e in esf_format.load_document(data, catalog).extra: + if isinstance(e, esf_format.TextExtra): + line = {"name": e.name, "version": e.version, "text": e.text} + else: + line = {"field": e.field, "bytes": esf_format.to_base64url(e.bytes)} + print(json.dumps(line)) + return 0 + fits = esf_format.load(data, catalog) if command == "canonical": sys.stdout.buffer.write(esf_format.save(fits, catalog).encode()) elif command == "binary": diff --git a/tests/test_document.py b/tests/test_document.py new file mode 100644 index 0000000..f4018c6 --- /dev/null +++ b/tests/test_document.py @@ -0,0 +1,141 @@ +import base64 +import os +import tomllib +from pathlib import Path + +import pytest +from test_api import CATALOG, RIFTER + +from esf_format import ( + BinaryExtra, + Document, + EsfFit, + EsfFormatError, + TextExtra, + binary_field, + from_base64url, + load, + load_document, + save, + save_binary, +) + +VALID = Path(os.environ.get("ESF_TESTS", "esf-format/tests")) / "valid" + + +def _input(case: Path) -> bytes: + if (case / "input.b64").exists(): + return from_base64url((case / "input.b64").read_text()) + return (case / "input.esf").read_bytes() + + +def _expected(case: Path) -> list[TextExtra | BinaryExtra]: + path = case / "extra.toml" + if not path.exists(): + return [] + out: list[TextExtra | BinaryExtra] = [] + for e in tomllib.loads(path.read_text())["extra"]: + if "field" in e: + raw = e["bytes"] + out.append( + BinaryExtra(e["field"], base64.urlsafe_b64decode(raw + "=" * (-len(raw) % 4))) + ) + else: + out.append(TextExtra(e["name"], e["version"], e["text"])) + return out + + +@pytest.mark.parametrize("case", sorted(VALID.iterdir()), ids=lambda p: p.name) +def test_valid_cases(case: Path) -> None: + data = _input(case) + document = load_document(data, CATALOG) + assert document.extra == _expected(case) + assert document.fits == load(data, CATALOG) + + +def test_cases_with_extra_exist() -> None: + assert sum(1 for c in VALID.iterdir() if (c / "extra.toml").exists()) >= 4 + + +def test_text_extra() -> None: + data = "%a/1\r\nx\r\n%esf/1\nRifter\n%b/22\n\n\n%c/3\n%d/0" + document = load_document(data, CATALOG) + assert document.extra == [ + TextExtra("a", 1, "x\r\n"), + TextExtra("b", 22, "\n\n"), + TextExtra("c", 3, ""), + TextExtra("d", 0, ""), + ] + assert document.fits == load(data, CATALOG) + + +def test_text_extra_unicode() -> None: + document = load_document("%esf/1\nRifter\n%x/1\nŝ €\n".encode(), CATALOG) + assert document.extra == [TextExtra("x", 1, "ŝ €\n")] + + +def test_no_extra() -> None: + fits = [EsfFit(RIFTER)] + assert load_document(save(fits, CATALOG), CATALOG) == Document( + load(save(fits, CATALOG), CATALOG) + ) + assert load_document(save_binary(fits, CATALOG), CATALOG).extra == [] + + +def test_unknown_esf_version() -> None: + with pytest.raises(EsfFormatError): + load_document("%esf/1\nRifter\n%esf/2\nRifter\n", CATALOG) + + +@pytest.mark.parametrize("version", ["4294967296", "9" * 5000]) +def test_text_extra_version_too_large(version: str) -> None: + with pytest.raises(EsfFormatError): + load_document(f"%esf/1\nRifter\n%x/{version}\n", CATALOG) + + +def test_load_skips_version_too_large() -> None: + data = "%esf/1\nRifter\n%fleet/99999999999\n" + assert load(data, CATALOG) == [EsfFit(RIFTER)] + with pytest.raises(EsfFormatError): + load_document(data, CATALOG) + + +def test_text_extra_version_max() -> None: + document = load_document("%esf/1\nRifter\n%x/0004294967295\n", CATALOG) + assert document.extra == [TextExtra("x", 4294967295, "")] + + +def test_binary_field_round_trip() -> None: + fits = [EsfFit(RIFTER)] + data = save_binary(fits, CATALOG) + binary_field(2, b"\x01\x02") + binary_field(1000, b"") + document = load_document(data, CATALOG) + assert document.fits == load(save_binary(fits, CATALOG), CATALOG) + assert document.extra == [BinaryExtra(2, b"\x01\x02"), BinaryExtra(1000, b"")] + + +def test_binary_field_before_fits() -> None: + data = binary_field(536870911, b"x") + save_binary([EsfFit(RIFTER)], CATALOG) + document = load_document(data, CATALOG) + assert document.extra == [BinaryExtra(536870911, b"x")] + assert document.fits[0].hull == RIFTER + + +def test_binary_skips_other_wire_types() -> None: + varint = bytes([2 << 3 | 0, 5]) + fixed64 = bytes([3 << 3 | 1]) + bytes(8) + fixed32 = bytes([4 << 3 | 5]) + bytes(4) + group = bytes([5 << 3 | 3]) + binary_field(6, b"in") + bytes([5 << 3 | 4]) + data = save_binary([EsfFit(RIFTER)], CATALOG) + varint + fixed64 + fixed32 + group + assert load_document(data, CATALOG).extra == [] + + +@pytest.mark.parametrize("field", [-1, 0, 1, 536870912]) +def test_binary_field_rejects(field: int) -> None: + with pytest.raises(ValueError): + binary_field(field, b"") + + +def test_binary_field_takes_bytes_like() -> None: + assert binary_field(2, bytearray(b"ab")) == b"\x12\x02ab" + with pytest.raises(TypeError): + binary_field(2, 5) # type: ignore[arg-type]