Skip to content
Draft
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
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
30 changes: 29 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down Expand Up @@ -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
Expand Down
56 changes: 48 additions & 8 deletions src/esf_format/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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",
Expand All @@ -65,25 +71,46 @@ 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
fit, entry = where[e.line - 1]
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:
Expand All @@ -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()
Expand Down
9 changes: 6 additions & 3 deletions src/esf_format/binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
54 changes: 54 additions & 0 deletions src/esf_format/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
22 changes: 19 additions & 3 deletions src/esf_format/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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:
Expand All @@ -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)
Expand All @@ -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:
Expand All @@ -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
1 change: 1 addition & 0 deletions src/esf_format/wire.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
14 changes: 12 additions & 2 deletions tests/program.py
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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":
Expand Down
Loading