Skip to content

comicbox.readinglists.transform ¶

Base class for converting a format’s document to and from the model.

A sibling of BaseTransform, not a subclass. BaseTransform compiles glom keypath specs and loads its result as a comic; a reading list is a list of nested rows, so each format converts with builder functions, and the result is a reading list.

ReadingListTransform ¶

Convert one format’s document to and from the reading-list model.

One instance serves one call. warnings collects what the call had to drop or guess, for the caller to show; the library does not log them.

Source code in comicbox/readinglists/transform.py
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
class ReadingListTransform:
    """
    Convert one format's document to and from the reading-list model.

    One instance serves one call. ``warnings`` collects what the call had
    to drop or guess, for the caller to show; the library does not log
    them.
    """

    SCHEMA_CLASS: type[BaseSchema] = ReadingListYamlSchema

    def __init__(self, path: Path | str | None = None) -> None:
        """Get the schema and start an empty warnings list."""
        self._path = path
        self._schema: BaseSchema = get_schema(self.SCHEMA_CLASS, path=path)
        self.warnings: list[str] = []

    @property
    def root_tag(self) -> str:
        """The root tag of this format's documents."""
        return self._schema.ROOT_TAG

    # Keys a format leaves out of its schema on purpose, so dropping them is
    # not worth a warning.
    IGNORED_KEYS: frozenset[str] = frozenset()

    def parse(self, text: str) -> dict[str, Any]:
        """Parse text, then load it through this format's schema."""
        try:
            document = self._schema.opts.render_module.loads(text)
        except _PARSE_ERRORS as exc:
            raise ReadingListFormatError(describe_syntax_error(exc)) from exc
        return self.from_document(document)

    def parse_data(
        self,
        data: str | bytes | bytearray,  # noqa: ARG002 - the CBL transform reads it
        text: str,
        *,
        replaced: bool,
    ) -> dict[str, Any]:
        """
        Parse a document as it was read: its bytes, and the text they decode to.

        ``replaced`` says the bytes were not UTF-8, so the text has U+FFFD
        in their place; that is a warning. A format that decodes its own
        bytes, as XML does by its declaration, parses ``data`` instead.
        """
        if replaced:
            self.warnings.append(NOT_UTF8)
        return self.parse(text)

    def from_document(self, document: Any) -> dict[str, Any]:
        """Load a parsed document through this format's schema."""
        if not isinstance(document, Mapping) or self.root_tag not in document:
            reason = f"No '{self.root_tag}' root found."
            raise ReadingListFormatError(reason)
        loaded = self.load_document(document)
        if not loaded:
            reason = f"Nothing readable under '{self.root_tag}'."
            raise ReadingListFormatError(reason)
        return loaded

    def load_document(self, document: Mapping[str, Any]) -> dict[str, Any]:
        """Load a parsed document through the schema, naming what it drops."""
        with unlogged_drops():
            loaded: dict[str, Any] = self._schema.load(document)  # pyright: ignore[reportAssignmentType]
        self.warnings.extend(describe_changes(document, loaded, "", self.IGNORED_KEYS))
        return loaded

    def render(self, document: Mapping[str, Any]) -> str:
        """Serialize a document with this format's schema."""
        return self._schema.dumps(document)

    def to_reading_list(self, data: Mapping[str, Any]) -> dict[str, Any]:
        """Convert a parsed document to the model's inner mapping."""
        root = data.get(self.root_tag) or {}
        if not isinstance(root, Mapping):
            reason = f"'{self.root_tag}' holds {type(root).__name__}, not a list."
            raise ReadingListFormatError(reason)
        return dict(root)

    def from_reading_list(self, reading_list: Mapping[str, Any]) -> dict[str, Any]:
        """Convert the model's inner mapping to a document for this format."""
        return {self.root_tag: dict(reading_list)}

    def unwritable(self, reading_list: Mapping[str, Any]) -> tuple[int, ...]:
        """List the positions, from 0, of entries this format cannot write."""
        del reading_list
        return ()

root_tag property ¶

The root tag of this format’s documents.

__init__(path=None) ¶

Get the schema and start an empty warnings list.

Source code in comicbox/readinglists/transform.py
79
80
81
82
83
def __init__(self, path: Path | str | None = None) -> None:
    """Get the schema and start an empty warnings list."""
    self._path = path
    self._schema: BaseSchema = get_schema(self.SCHEMA_CLASS, path=path)
    self.warnings: list[str] = []

from_document(document) ¶

Load a parsed document through this format’s schema.

Source code in comicbox/readinglists/transform.py
120
121
122
123
124
125
126
127
128
129
def from_document(self, document: Any) -> dict[str, Any]:
    """Load a parsed document through this format's schema."""
    if not isinstance(document, Mapping) or self.root_tag not in document:
        reason = f"No '{self.root_tag}' root found."
        raise ReadingListFormatError(reason)
    loaded = self.load_document(document)
    if not loaded:
        reason = f"Nothing readable under '{self.root_tag}'."
        raise ReadingListFormatError(reason)
    return loaded

from_reading_list(reading_list) ¶

Convert the model’s inner mapping to a document for this format.

Source code in comicbox/readinglists/transform.py
150
151
152
def from_reading_list(self, reading_list: Mapping[str, Any]) -> dict[str, Any]:
    """Convert the model's inner mapping to a document for this format."""
    return {self.root_tag: dict(reading_list)}

load_document(document) ¶

Load a parsed document through the schema, naming what it drops.

Source code in comicbox/readinglists/transform.py
131
132
133
134
135
136
def load_document(self, document: Mapping[str, Any]) -> dict[str, Any]:
    """Load a parsed document through the schema, naming what it drops."""
    with unlogged_drops():
        loaded: dict[str, Any] = self._schema.load(document)  # pyright: ignore[reportAssignmentType]
    self.warnings.extend(describe_changes(document, loaded, "", self.IGNORED_KEYS))
    return loaded

parse(text) ¶

Parse text, then load it through this format’s schema.

Source code in comicbox/readinglists/transform.py
 94
 95
 96
 97
 98
 99
100
def parse(self, text: str) -> dict[str, Any]:
    """Parse text, then load it through this format's schema."""
    try:
        document = self._schema.opts.render_module.loads(text)
    except _PARSE_ERRORS as exc:
        raise ReadingListFormatError(describe_syntax_error(exc)) from exc
    return self.from_document(document)

parse_data(data, text, *, replaced) ¶

Parse a document as it was read: its bytes, and the text they decode to.

replaced says the bytes were not UTF-8, so the text has U+FFFD in their place; that is a warning. A format that decodes its own bytes, as XML does by its declaration, parses data instead.

Source code in comicbox/readinglists/transform.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def parse_data(
    self,
    data: str | bytes | bytearray,  # noqa: ARG002 - the CBL transform reads it
    text: str,
    *,
    replaced: bool,
) -> dict[str, Any]:
    """
    Parse a document as it was read: its bytes, and the text they decode to.

    ``replaced`` says the bytes were not UTF-8, so the text has U+FFFD
    in their place; that is a warning. A format that decodes its own
    bytes, as XML does by its declaration, parses ``data`` instead.
    """
    if replaced:
        self.warnings.append(NOT_UTF8)
    return self.parse(text)

render(document) ¶

Serialize a document with this format’s schema.

Source code in comicbox/readinglists/transform.py
138
139
140
def render(self, document: Mapping[str, Any]) -> str:
    """Serialize a document with this format's schema."""
    return self._schema.dumps(document)

to_reading_list(data) ¶

Convert a parsed document to the model’s inner mapping.

Source code in comicbox/readinglists/transform.py
142
143
144
145
146
147
148
def to_reading_list(self, data: Mapping[str, Any]) -> dict[str, Any]:
    """Convert a parsed document to the model's inner mapping."""
    root = data.get(self.root_tag) or {}
    if not isinstance(root, Mapping):
        reason = f"'{self.root_tag}' holds {type(root).__name__}, not a list."
        raise ReadingListFormatError(reason)
    return dict(root)

unwritable(reading_list) ¶

List the positions, from 0, of entries this format cannot write.

Source code in comicbox/readinglists/transform.py
154
155
156
157
def unwritable(self, reading_list: Mapping[str, Any]) -> tuple[int, ...]:
    """List the positions, from 0, of entries this format cannot write."""
    del reading_list
    return ()

entry_issue_name(entry) ¶

Get an entry’s issue name, or build it from the number and suffix.

Source code in comicbox/readinglists/transform.py
58
59
60
61
62
63
64
65
def entry_issue_name(entry: Mapping[str, Any]) -> str:
    """Get an entry's issue name, or build it from the number and suffix."""
    issue = entry.get(ISSUE_KEY) or {}
    if name := issue.get(NAME_KEY):
        return str(name)
    number = issue.get(NUMBER_KEY)
    number = "" if number is None else number
    return f"{number}{issue.get(ISSUE_SUFFIX_KEY) or ''}".strip()

issue_id(entry, source) ¶

Get an entry’s issue id for a database, ignoring other id types.

Source code in comicbox/readinglists/transform.py
43
44
45
46
47
48
def issue_id(entry: Mapping[str, Any], source: str) -> str:
    """Get an entry's issue id for a database, ignoring other id types."""
    identifier = (entry.get(IDENTIFIERS_KEY) or {}).get(source) or {}
    if (identifier.get(ID_TYPE_KEY) or DEFAULT_ID_TYPE) != DEFAULT_ID_TYPE:
        return ""
    return str(identifier.get(ID_KEY_KEY) or "")

series_id(entry, source) ¶

Get an entry’s series id for a database.

Source code in comicbox/readinglists/transform.py
51
52
53
54
55
def series_id(entry: Mapping[str, Any], source: str) -> str:
    """Get an entry's series id for a database."""
    series = entry.get(SERIES_KEY) or {}
    identifier = (series.get(IDENTIFIERS_KEY) or {}).get(source) or {}
    return str(identifier.get(ID_KEY_KEY) or "")