Skip to content

comicbox.readinglists.serialize

Read and write reading lists in any registered format.

ReadingListResult dataclass

A reading list read from a document or fetched from a database.

reading_list is the model’s inner mapping. fmt is the format the document was in, or None for a list built from an online database’s records, such as a Metron reading list. warnings name every key or value the read dropped, changed or guessed, each starting with its path; they are returned, not logged.

Source code in comicbox/readinglists/serialize.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
@dataclass(frozen=True, slots=True)
class ReadingListResult:
    """
    A reading list read from a document or fetched from a database.

    ``reading_list`` is the model's inner mapping. ``fmt`` is the format the
    document was in, or None for a list built from an online database's
    records, such as a Metron reading list. ``warnings`` name every key or
    value the read dropped, changed or guessed, each starting with its
    path; they are returned, not logged.
    """

    reading_list: dict[str, Any]
    fmt: ReadingListFormats | None
    warnings: tuple[str, ...] = ()

dumps(reading_list, fmt)

Write a reading list in a format.

The list is validated against the model first, so a hand-built mapping is checked before it is written. lost_fields says what the format cannot carry.

Source code in comicbox/readinglists/serialize.py
277
278
279
280
281
282
283
284
285
286
287
def dumps(reading_list: Mapping[str, Any], fmt: ReadingListFormats | str) -> str:
    """
    Write a reading list in a format.

    The list is validated against the model first, so a hand-built mapping
    is checked before it is written. ``lost_fields`` says what the format
    cannot carry.
    """
    transform = get_format(fmt).value.transform_class()
    document = transform.from_reading_list(_model_for_write(reading_list))
    return transform.render(document)

load(path, *, fmt=None)

Read a reading list from a file, detecting its format if not given.

Source code in comicbox/readinglists/serialize.py
261
262
263
264
265
266
def load(
    path: Path | str, *, fmt: ReadingListFormats | str | None = None
) -> ReadingListResult:
    """Read a reading list from a file, detecting its format if not given."""
    path = Path(path)
    return _loads(path.read_bytes(), fmt, path)

load_model(reading_list, path=None)

Validate a list against the model, dropping what does not fit.

Source code in comicbox/readinglists/serialize.py
193
194
195
196
197
def load_model(
    reading_list: Mapping[str, Any], path: Path | None = None
) -> dict[str, Any]:
    """Validate a list against the model, dropping what does not fit."""
    return load_model_with_warnings(reading_list, path)[0]

load_model_with_warnings(reading_list, path=None)

Validate a list against the model, naming everything that does not fit.

Each warning starts with the path of what was dropped or changed: start_year, entries #3.series. They are returned, not logged.

Source code in comicbox/readinglists/serialize.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
def load_model_with_warnings(
    reading_list: Mapping[str, Any], path: Path | None = None
) -> tuple[dict[str, Any], tuple[str, ...]]:
    """
    Validate a list against the model, naming everything that does not fit.

    Each warning starts with the path of what was dropped or changed:
    ``start_year``, ``entries #3.series``. They are returned, not logged.
    """
    warnings: list[str] = []
    with readable_depth():
        raw = dict(clean_tree(unwrap(reading_list), warnings))
        _string_tags(raw, warnings)
        raw_entries = raw.pop(ENTRIES_KEY, None)
        schema = get_schema(ReadingListYamlSchema, path=path)
        with unlogged_drops():
            loaded: dict[str, Any] = schema.load({READING_LIST_KEY: raw})  # pyright: ignore[reportAssignmentType]
            header = dict(loaded.get(READING_LIST_KEY) or {})
            warnings.extend(describe_changes(raw, header))
            if entries := _load_entries(raw_entries, warnings):
                header[ENTRIES_KEY] = entries
    return header, tuple(warnings)

loads(data, *, fmt=None)

Read a reading list from a string or bytes, detecting its format.

Bytes are UTF-8, except XML, which is read in the encoding it declares.

Source code in comicbox/readinglists/serialize.py
250
251
252
253
254
255
256
257
258
def loads(
    data: str | bytes | bytearray, *, fmt: ReadingListFormats | str | None = None
) -> ReadingListResult:
    """
    Read a reading list from a string or bytes, detecting its format.

    Bytes are UTF-8, except XML, which is read in the encoding it declares.
    """
    return _loads(data, fmt, None)

lost_fields(reading_list, fmt)

Name what writing this list in a format and reading it back would change.

Exact: the list is written, read back and compared. Header keys such as sources, entry paths such as entries.date.cover_date, and entries #2, #5 for entries the format cannot write at all.

Source code in comicbox/readinglists/serialize.py
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
def lost_fields(
    reading_list: Mapping[str, Any], fmt: ReadingListFormats | str
) -> tuple[str, ...]:
    """
    Name what writing this list in a format and reading it back would change.

    Exact: the list is written, read back and compared. Header keys such as
    ``sources``, entry paths such as ``entries.date.cover_date``, and
    ``entries #2, #5`` for entries the format cannot write at all.
    """
    resolved = get_format(fmt)
    model = _model_for_write(reading_list)
    transform = resolved.value.transform_class()
    text = transform.render(transform.from_reading_list(model))
    back = _loads(text, resolved, None).reading_list
    return describe_losses(model, back, transform.unwritable(model))

readable_depth()

Turn nesting too deep for the parsers into a format error.

Source code in comicbox/readinglists/serialize.py
43
44
45
46
47
48
49
50
51
@contextmanager
def readable_depth() -> Generator[None]:
    """Turn nesting too deep for the parsers into a format error."""
    try:
        yield
    except RecursionError:
        reason = "The document is nested too deeply to read."
        # From None: the recursion's own traceback is thousands of frames.
        raise ReadingListFormatError(reason) from None

resolve_format(text, fmt=None)

Name the format given, else detect it, else raise with the reason.

A YAML document that uses an alias is refused here, before anything parses or validates it whole.

Source code in comicbox/readinglists/serialize.py
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def resolve_format(
    text: str, fmt: ReadingListFormats | str | None = None
) -> ReadingListFormats:
    """
    Name the format given, else detect it, else raise with the reason.

    A YAML document that uses an alias is refused here, before anything
    parses or validates it whole.
    """
    with readable_depth():
        resolved = get_format(fmt) if fmt else detect_format(text)
        if resolved is None:
            reason = (
                syntax_error(text) or "Not a reading list in any format comicbox reads."
            )
            raise ReadingListFormatError(reason)
    if resolved.value.lexer == _YAML_LEXER:
        refuse_yaml_aliases(text)
    return resolved

unwrap(reading_list)

Accept a list wrapped in its root tag, as a serialized document is.

Source code in comicbox/readinglists/serialize.py
71
72
73
74
75
76
77
def unwrap(reading_list: Mapping[str, Any]) -> Mapping[str, Any]:
    """Accept a list wrapped in its root tag, as a serialized document is."""
    if set(reading_list) == {READING_LIST_KEY}:
        inner = reading_list[READING_LIST_KEY]
        if isinstance(inner, Mapping):
            return inner
    return reading_list