Skip to content

comicbox.readinglists

Reading lists: read, combine and write lists of comics in reading order.

Everything codex uses comes from this package. Nothing outside it imports it at module load, and it imports no network library, so a normal comicbox run does not pay for it.

Catalog dataclass

The index of one repository at one ref.

etag revalidates it; fetched is when GitHub last confirmed it.

Source code in comicbox/readinglists/sources/catalog.py
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
@dataclass(frozen=True, slots=True)
class Catalog:
    """
    The index of one repository at one ref.

    ``etag`` revalidates it; ``fetched`` is when GitHub last confirmed it.
    """

    repo: str
    ref: str
    etag: str | None
    fetched: datetime
    entries: tuple[CatalogEntry, ...]

    def find(self, path: str, sha: str | None = None) -> CatalogEntry | None:
        """
        Find a list by path, else by blob sha, if one is given.

        Copies share a sha. Among them, the one with the old path's file
        name wins, then the one in its folder; if that leaves more than
        one, ``ReadingListFetchError`` names them rather than guess.
        """
        by_path = next((entry for entry in self.entries if entry.path == path), None)
        if by_path is not None or not sha:
            return by_path
        return _one_copy([entry for entry in self.entries if entry.sha == sha], path)

    def search(self, query: str) -> tuple[CatalogEntry, ...]:
        """Find the lists whose path holds every word of ``query``."""
        if not (words := fold_text(query).split()):
            return ()
        return tuple(
            entry
            for entry in self.entries
            if all(word in fold_text(entry.path) for word in words)
        )

find(path, sha=None)

Find a list by path, else by blob sha, if one is given.

Copies share a sha. Among them, the one with the old path’s file name wins, then the one in its folder; if that leaves more than one, ReadingListFetchError names them rather than guess.

Source code in comicbox/readinglists/sources/catalog.py
131
132
133
134
135
136
137
138
139
140
141
142
def find(self, path: str, sha: str | None = None) -> CatalogEntry | None:
    """
    Find a list by path, else by blob sha, if one is given.

    Copies share a sha. Among them, the one with the old path's file
    name wins, then the one in its folder; if that leaves more than
    one, ``ReadingListFetchError`` names them rather than guess.
    """
    by_path = next((entry for entry in self.entries if entry.path == path), None)
    if by_path is not None or not sha:
        return by_path
    return _one_copy([entry for entry in self.entries if entry.sha == sha], path)

search(query)

Find the lists whose path holds every word of query.

Source code in comicbox/readinglists/sources/catalog.py
144
145
146
147
148
149
150
151
152
def search(self, query: str) -> tuple[CatalogEntry, ...]:
    """Find the lists whose path holds every word of ``query``."""
    if not (words := fold_text(query).split()):
        return ()
    return tuple(
        entry
        for entry in self.entries
        if all(word in fold_text(entry.path) for word in words)
    )

CatalogEntry dataclass

One list in the catalog.

publisher and category are the first two folders of its path, when it has them. curator is the site the list was taken from, from the file name or a folder, in the model’s spelling.

Source code in comicbox/readinglists/sources/catalog.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
@dataclass(frozen=True, slots=True)
class CatalogEntry:
    """
    One list in the catalog.

    ``publisher`` and ``category`` are the first two folders of its path,
    when it has them. ``curator`` is the site the list was taken from, from
    the file name or a folder, in the model's spelling.
    """

    path: str
    sha: str
    size: int
    publisher: str | None = None
    category: str | None = None
    curator: str | None = None

    @property
    def name(self) -> str:
        """The file name without its ``.cbl``."""
        return PurePosixPath(self.path).stem

name property

The file name without its .cbl.

CombineResult dataclass

The combined list and what combining found.

provenance is parallel to the list’s entries: the rows each came from, in rank order. only_in is indexed by input: the entries no other input has. name_joins are the entries some row joined on a series name alone, with a start year, volume or cover year: the joins most likely to be wrong. shared_ids are the ids left on more than one entry that no input repeats.

Source code in comicbox/readinglists/combine/__init__.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
@dataclass(frozen=True, slots=True)
class CombineResult:
    """
    The combined list and what combining found.

    ``provenance`` is parallel to the list's entries: the rows each came
    from, in rank order. ``only_in`` is indexed by input: the entries no
    other input has. ``name_joins`` are the entries some row joined on a
    series name alone, with a start year, volume or cover year: the joins
    most likely to be wrong. ``shared_ids`` are the ids left on more than
    one entry that no input repeats.
    """

    reading_list: dict[str, Any]
    provenance: tuple[tuple[EntryOrigin, ...], ...]
    only_in: tuple[tuple[int, ...], ...]
    order_conflicts: tuple[OrderConflict, ...]
    id_conflicts: tuple[IdConflict, ...]
    name_joins: tuple[int, ...]
    shared_ids: tuple[SharedId, ...] = ()

Comparison dataclass

How two lists compare.

overlap is the shared issues over all issues. contains is the share of a found in b, then of b found in a. order_agreement is the longest common subsequence of the shared issues over their count, or None when either list is marked unordered, since such a list has no order to agree with.

Source code in comicbox/readinglists/compare.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
@dataclass(frozen=True, slots=True)
class Comparison:
    """
    How two lists compare.

    ``overlap`` is the shared issues over all issues. ``contains`` is the
    share of ``a`` found in ``b``, then of ``b`` found in ``a``.
    ``order_agreement`` is the longest common subsequence of the shared
    issues over their count, or None when either list is marked unordered,
    since such a list has no order to agree with.
    """

    verdict: Verdict
    overlap: float
    contains: tuple[float, float]
    order_agreement: float | None

Discriminators dataclass

What a row tells its volume by: up to one discriminator of each kind.

year is the year-like one: the start year or, failing that, a volume number of 1900 or more, as a CBL’s Volume="2006" is. volume is a volume number under 1900. Z-Men (1991) volume 2 has both.

Source code in comicbox/readinglists/identity.py
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
@dataclass(frozen=True, slots=True)
class Discriminators:
    """
    What a row tells its volume by: up to one discriminator of each kind.

    ``year`` is the year-like one: the start year or, failing that, a volume
    number of 1900 or more, as a CBL's ``Volume="2006"`` is. ``volume`` is a
    volume number under 1900. Z-Men (1991) volume 2 has both.
    """

    year: int | None = None
    volume: int | None = None

    def shares_a_kind(self, other: "Discriminators") -> bool:
        """Tell whether two rows have a discriminator of one kind each."""
        return (self.year is not None and other.year is not None) or (
            self.volume is not None and other.volume is not None
        )

    def conflicts(self, other: "Discriminators") -> bool:
        """
        Tell whether two rows are of two volumes.

        They conflict when they have a discriminator of the same kind and
        those differ, in either kind: the 2011 and 2016 volumes, or volumes 1
        and 2. A start year and volume 2 cannot be compared.
        """
        return _differ(self.year, other.year) or _differ(self.volume, other.volume)

conflicts(other)

Tell whether two rows are of two volumes.

They conflict when they have a discriminator of the same kind and those differ, in either kind: the 2011 and 2016 volumes, or volumes 1 and 2. A start year and volume 2 cannot be compared.

Source code in comicbox/readinglists/identity.py
171
172
173
174
175
176
177
178
179
def conflicts(self, other: "Discriminators") -> bool:
    """
    Tell whether two rows are of two volumes.

    They conflict when they have a discriminator of the same kind and
    those differ, in either kind: the 2011 and 2016 volumes, or volumes 1
    and 2. A start year and volume 2 cannot be compared.
    """
    return _differ(self.year, other.year) or _differ(self.volume, other.volume)

shares_a_kind(other)

Tell whether two rows have a discriminator of one kind each.

Source code in comicbox/readinglists/identity.py
165
166
167
168
169
def shares_a_kind(self, other: "Discriminators") -> bool:
    """Tell whether two rows have a discriminator of one kind each."""
    return (self.year is not None and other.year is not None) or (
        self.volume is not None and other.volume is not None
    )

EntryOrigin dataclass

A row of an input: input_index ranks the input, row its entry.

Source code in comicbox/readinglists/combine/__init__.py
46
47
48
49
50
51
@dataclass(frozen=True, slots=True)
class EntryOrigin:
    """A row of an input: ``input_index`` ranks the input, ``row`` its entry."""

    input_index: int
    row: int

IdConflict dataclass

Two values for one source on one issue: one of the lists is wrong.

Combined entry entry keeps kept for source, a database; the row at input_index and row, joined to it, had dropped. A barcode that differs is a printing or an edition, so it is never one.

Source code in comicbox/readinglists/combine/__init__.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
@dataclass(frozen=True, slots=True)
class IdConflict:
    """
    Two values for one source on one issue: one of the lists is wrong.

    Combined entry ``entry`` keeps ``kept`` for ``source``, a database; the
    row at ``input_index`` and ``row``, joined to it, had ``dropped``. A
    barcode that differs is a printing or an edition, so it is never one.
    """

    entry: int
    source: str
    kept: str
    dropped: str
    input_index: int
    row: int

MetronListSummary dataclass

One reading list a Metron search found.

curator is the site the list was taken from, lowercased like a fetched list’s source, or None. rating is the average of rating_count ratings, or None when there are none.

Source code in comicbox/readinglists/formats/metron_api.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
@dataclass(frozen=True, slots=True)
class MetronListSummary:
    """
    One reading list a Metron search found.

    ``curator`` is the site the list was taken from, lowercased like a
    fetched list's source, or None. ``rating`` is the average of
    ``rating_count`` ratings, or None when there are none.
    """

    id: int
    name: str
    list_type: str
    private: bool
    curator: str | None
    username: str
    rating: float | None
    rating_count: int
    modified: datetime

OrderConflict dataclass

An input puts combined entry entry somewhere the backbone does not.

Source code in comicbox/readinglists/combine/__init__.py
54
55
56
57
58
59
60
@dataclass(frozen=True, slots=True)
class OrderConflict:
    """An input puts combined entry ``entry`` somewhere the backbone does not."""

    entry: int
    input_index: int
    row: int

ParsedIssue dataclass

An issue name, normalized, and the number and suffix read out of it.

Source code in comicbox/readinglists/identity.py
61
62
63
64
65
66
67
@dataclass(frozen=True, slots=True)
class ParsedIssue:
    """An issue name, normalized, and the number and suffix read out of it."""

    name: str
    number: Decimal | None
    suffix: str

ReadingListError

Bases: ComicboxError

A reading list could not be read, converted, combined or written.

Source code in comicbox/exceptions.py
140
141
class ReadingListError(ComicboxError):
    """A reading list could not be read, converted, combined or written."""

ReadingListFetchError

Bases: ReadingListError

A reading list could not be fetched.

A network failure, an HTTP error, a refused URL, a download over the size cap, or a missing credential. A cancel, or a spent quota, raises OnlineLookupAbortedError instead, as tagging does.

Source code in comicbox/exceptions.py
157
158
159
160
161
162
163
164
class ReadingListFetchError(ReadingListError):
    """
    A reading list could not be fetched.

    A network failure, an HTTP error, a refused URL, a download over the
    size cap, or a missing credential. A cancel, or a spent quota, raises
    ``OnlineLookupAbortedError`` instead, as tagging does.
    """

ReadingListFormat dataclass

A reading-list file format.

Frozen because it is an enum value. tokens are the names the CLI and the API accept for it, unique across formats. validator_spec names a schema file under comicbox/schemas/, built only when something validates.

Source code in comicbox/readinglists/formats/__init__.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
@dataclass(frozen=True, slots=True)
class ReadingListFormat:
    """
    A reading-list file format.

    Frozen because it is an enum value. ``tokens`` are the names the CLI and
    the API accept for it, unique across formats. ``validator_spec`` names a
    schema file under ``comicbox/schemas/``, built only when something
    validates.
    """

    label: str
    tokens: frozenset[str]
    suffix: str
    transform_class: type[ReadingListTransform]
    lexer: str = "yaml"
    validator_spec: ValidatorSpec | None = None

    @property
    def schema_class(self) -> type[BaseSchema]:
        """The transform's schema class."""
        return self.transform_class.SCHEMA_CLASS

schema_class property

The transform’s schema class.

ReadingListFormatError

Bases: ReadingListError

A document is not a reading list in any format comicbox reads.

Source code in comicbox/exceptions.py
144
145
class ReadingListFormatError(ReadingListError):
    """A document is not a reading list in any format comicbox reads."""

ReadingListFormats

Bases: Enum

Reading-list file formats.

Source code in comicbox/readinglists/registry.py
35
36
37
38
39
40
41
class ReadingListFormats(Enum):
    """Reading-list file formats."""

    YAML = YAML_REGISTRATION
    JSON = JSON_REGISTRATION
    CBL = CBL_REGISTRATION
    JSON_CBL = JSON_CBL_REGISTRATION

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, ...] = ()

ReadingListSession

Fetch reading lists from URLs and online sources.

credentials are an OnlineCredentials, as OnlineSession takes; without them the config’s online.auth is used. config is a ComicboxSettings; without it the usual config files and environment are read once. on_event receives the ReadingListFetch* events. client_name names the embedding application in the outgoing User-Agent.

A context manager: leaving it closes the connections the session opened.

Source code in comicbox/readinglists/session.py
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
class ReadingListSession:
    """
    Fetch reading lists from URLs and online sources.

    ``credentials`` are an ``OnlineCredentials``, as ``OnlineSession``
    takes; without them the config's ``online.auth`` is used. ``config``
    is a ``ComicboxSettings``; without it the usual config files and
    environment are read once. ``on_event`` receives the
    ``ReadingListFetch*`` events. ``client_name`` names the embedding
    application in the outgoing User-Agent.

    A context manager: leaving it closes the connections the session
    opened.
    """

    def __init__(
        self,
        *,
        credentials: OnlineCredentials | None = None,
        config: ComicboxSettings | None = None,
        on_event: EventHandler | None = None,
        client_name: str | None = None,
    ) -> None:
        """Read the config once; open nothing until the first fetch."""
        if client_name is not None:
            # Set before any client exists: clients bake the header in.
            set_user_agent_context("lib", client=client_name)
        self._credentials = credentials
        self._settings: ComicboxSettings = (
            config if config is not None else get_config()
        )
        self._on_event = on_event
        self._cancelled = threading.Event()
        self._http: httpx.Client | None = None
        # Tests and embedders may set an httpx transport before first use.
        self._transport: httpx.BaseTransport | None = None

    def __enter__(self) -> Self:
        """Use the session in a with block."""
        return self

    def __exit__(self, *_exc_info: object) -> None:
        """Close the session's connections."""
        self.close()

    @property
    def settings(self) -> ComicboxSettings:
        """The settings every fetch uses."""
        return self._settings

    @property
    def credentials(self) -> OnlineCredentials | None:
        """The credentials the session was given, if any."""
        return self._credentials

    def cancel(self) -> None:
        """Stop the session: the fetch under way, or the next, raises."""
        self._cancelled.set()

    def close(self) -> None:
        """
        Close the HTTP client and Metron's shared sessions, if opened.

        Comic Vine's shared client is left open. Closing it closes its
        rate-limit buckets, which can fail a tagging lookup in the same
        process that holds one; ``OnlineSession.close`` releases it.
        """
        if self._http is not None:
            self._http.close()
            self._http = None
        if (metron := sys.modules.get(_METRON_SOURCE_MODULE)) is not None:
            metron.close_shared_sessions()

    # Internals shared by the sources.

    def check_cancelled(self) -> None:
        """Raise if the session was cancelled."""
        if self._cancelled.is_set():
            reason = "Reading-list fetch cancelled."
            raise OnlineLookupAbortedError(reason)

    @property
    def cancelled(self) -> threading.Event:
        """The event ``cancel()`` sets, for sources that wait."""
        return self._cancelled

    def emit(self, event: Event) -> None:
        """Hand an event to the caller's handler, if any."""
        if self._on_event is not None:
            self._on_event(event)

    def http(self) -> httpx.Client:
        """Get the session's HTTP client, built on first use."""
        if self._http is None:
            import httpx

            self._http = httpx.Client(
                follow_redirects=True,
                timeout=_TIMEOUT_SECONDS,
                headers={"User-Agent": user_agent()},
                transport=self._transport,
            )
        return self._http

    @contextmanager
    def fetching(self, kind: str, key: str) -> Generator[None]:
        """Bracket one fetch with its start and finish events."""
        self.check_cancelled()
        self.emit(ReadingListFetchStarted(source=kind, key=key))
        try:
            yield
        finally:
            self.emit(ReadingListFetchFinished(source=kind, key=key))

    def load_fetched(self, data: bytes, source: dict[str, Any]) -> ReadingListResult:
        """
        Read fetched bytes as a list from ``source``, detecting the format.

        A document that will not read names where it came from, as a
        file's error names its path.
        """
        try:
            result = loads(data)
        except ReadingListFormatError as exc:
            where = source.get(SOURCE_URL_KEY) or source.get(SOURCE_KEY_KEY)
            reason = f"{where}: {exc}"
            raise type(exc)(reason) from exc
        reading_list = attach_source(result.reading_list, source)
        return ReadingListResult(reading_list, result.fmt, result.warnings)

    # Fetches.

    def fetch_url(self, url: str) -> ReadingListResult:
        """
        Fetch a list from an http or https URL, in any format comicbox reads.

        Redirects are followed and the download is capped at
        ``readinglists.max_download_bytes``. Its source is of kind ``url``.
        A user name and password in the URL are sent, and never recorded.
        """
        from comicbox.readinglists.sources.url import fetch, without_userinfo

        kind = SourceKind.URL.value
        # A user name and password in the URL go with the request; they are
        # never recorded on the list, nor shown in an event or an error.
        shown = without_userinfo(url)
        with self.fetching(kind, shown):
            max_bytes = self._settings.readinglists.max_download_bytes
            data, revision = fetch(
                self.http(), url, max_bytes, cancelled=self._cancelled.is_set
            )
            self.check_cancelled()
            source = {
                SOURCE_KIND_KEY: kind,
                SOURCE_KEY_KEY: shown,
                SOURCE_URL_KEY: shown,
                SOURCE_REVISION_KEY: revision,
            }
            return self.load_fetched(data, source)

    def search_metron(
        self,
        *,
        name: str | None = None,
        curator: str | None = None,
        username: str | None = None,
        modified_since: datetime | None = None,
    ) -> list[MetronListSummary]:
        """
        Search Metron's reading lists: public ones and the token's own.

        ``curator`` is a site Metron credits lists to, such as ``cbro``.
        Needs a Metron API token.
        """
        from comicbox.readinglists.sources import metron

        self.check_cancelled()
        found = metron.search(
            self,
            name=name,
            curator=curator,
            username=username,
            modified_since=modified_since,
        )
        self.check_cancelled()
        return found

    def fetch_metron_list(
        self, list_id: int, *, if_modified_since: datetime | None = None
    ) -> ReadingListResult | None:
        """
        Fetch a Metron reading list, in its order.

        Returns None, having fetched no items, when the list is unchanged
        since ``if_modified_since``. Progress events count the items as
        their pages arrive. Needs a Metron API token. The result has no
        ``fmt``: it was read from no document.
        """
        from comicbox.readinglists.sources import metron

        metron.check_token(self)
        with self.fetching(SourceKind.METRON_LIST.value, str(list_id)):
            result = metron.fetch_list(
                self, list_id, if_modified_since=if_modified_since
            )
            # A cancel during the last request still cancels.
            self.check_cancelled()
            return result

    def fetch_metron_arc(
        self, arc_id: int, *, if_modified_since: datetime | None = None
    ) -> ReadingListResult | None:
        """
        Fetch a Metron story arc as an unordered list.

        Returns None, having fetched no issues, when the arc is unchanged
        since ``if_modified_since``. Needs a Metron API token.
        """
        from comicbox.readinglists.sources import metron

        metron.check_token(self)
        with self.fetching(SourceKind.METRON_ARC.value, str(arc_id)):
            result = metron.fetch_arc(self, arc_id, if_modified_since=if_modified_since)
            self.check_cancelled()
            return result

    def fetch_comicvine_arc(self, arc_id: int) -> ReadingListResult:
        """
        Fetch a Comic Vine story arc as an unordered list.

        Comic Vine names an arc's issues by id alone, so after the arc come
        its issues, a hundred a call, then their volumes the same way: an
        arc of N issues in V volumes costs ``1 + ceil(N/100) + ceil(V/100)``
        calls, each on its own hourly budget. Progress events count the
        issues as they arrive. A budget already spent fails the fetch at
        once, saying when it frees, rather than waiting.

        Comic Vine has no conditional request, so there is no
        ``if_modified_since``: compare the result's source revision instead.
        Needs a Comic Vine API key. The result has no ``fmt``.
        """
        from comicbox.readinglists.sources import comicvine

        comicvine.check_key(self)
        with self.fetching(SourceKind.COMICVINE_ARC.value, str(arc_id)):
            result = comicvine.fetch_arc(self, arc_id)
            self.check_cancelled()
            return result

    def catalog(self, *, refresh: bool = False) -> Catalog:
        """
        Get the index of the reading-list catalog on GitHub.

        The repository and ref are ``readinglists.catalog_repo`` and
        ``catalog_ref``. The index is cached under the online cache
        directory: within ``readinglists.catalog_ttl`` no request is made,
        and after it the cached index is revalidated. ``refresh`` asks
        GitHub now.
        """
        from comicbox.readinglists.sources.catalog import load_catalog

        self.check_cancelled()
        catalog = load_catalog(self, refresh=refresh)[0]
        self.check_cancelled()
        return catalog

    def search_catalog(self, query: str) -> tuple[CatalogEntry, ...]:
        """Find the catalog's lists whose path holds every word of ``query``."""
        return self.catalog().search(query)

    def fetch_catalog(self, path: str, *, sha: str | None = None) -> ReadingListResult:
        """
        Fetch a list from the catalog by its path.

        Paths change there; when ``path`` is gone and ``sha`` names the
        blob it had, the list with that sha is fetched in its place. The
        result's source is of kind ``catalog``, keyed by the path it was
        found at, with the blob sha as its revision.
        """
        from comicbox.readinglists.sources.catalog import fetch_entry

        with self.fetching(SourceKind.CATALOG.value, path):
            data, source = fetch_entry(self, path, sha)
            self.check_cancelled()
            return self.load_fetched(data, source)

cancelled property

The event cancel() sets, for sources that wait.

credentials property

The credentials the session was given, if any.

settings property

The settings every fetch uses.

__enter__()

Use the session in a with block.

Source code in comicbox/readinglists/session.py
87
88
89
def __enter__(self) -> Self:
    """Use the session in a with block."""
    return self

__exit__(*_exc_info)

Close the session’s connections.

Source code in comicbox/readinglists/session.py
91
92
93
def __exit__(self, *_exc_info: object) -> None:
    """Close the session's connections."""
    self.close()

__init__(*, credentials=None, config=None, on_event=None, client_name=None)

Read the config once; open nothing until the first fetch.

Source code in comicbox/readinglists/session.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def __init__(
    self,
    *,
    credentials: OnlineCredentials | None = None,
    config: ComicboxSettings | None = None,
    on_event: EventHandler | None = None,
    client_name: str | None = None,
) -> None:
    """Read the config once; open nothing until the first fetch."""
    if client_name is not None:
        # Set before any client exists: clients bake the header in.
        set_user_agent_context("lib", client=client_name)
    self._credentials = credentials
    self._settings: ComicboxSettings = (
        config if config is not None else get_config()
    )
    self._on_event = on_event
    self._cancelled = threading.Event()
    self._http: httpx.Client | None = None
    # Tests and embedders may set an httpx transport before first use.
    self._transport: httpx.BaseTransport | None = None

cancel()

Stop the session: the fetch under way, or the next, raises.

Source code in comicbox/readinglists/session.py
105
106
107
def cancel(self) -> None:
    """Stop the session: the fetch under way, or the next, raises."""
    self._cancelled.set()

catalog(*, refresh=False)

Get the index of the reading-list catalog on GitHub.

The repository and ref are readinglists.catalog_repo and catalog_ref. The index is cached under the online cache directory: within readinglists.catalog_ttl no request is made, and after it the cached index is revalidated. refresh asks GitHub now.

Source code in comicbox/readinglists/session.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
def catalog(self, *, refresh: bool = False) -> Catalog:
    """
    Get the index of the reading-list catalog on GitHub.

    The repository and ref are ``readinglists.catalog_repo`` and
    ``catalog_ref``. The index is cached under the online cache
    directory: within ``readinglists.catalog_ttl`` no request is made,
    and after it the cached index is revalidated. ``refresh`` asks
    GitHub now.
    """
    from comicbox.readinglists.sources.catalog import load_catalog

    self.check_cancelled()
    catalog = load_catalog(self, refresh=refresh)[0]
    self.check_cancelled()
    return catalog

check_cancelled()

Raise if the session was cancelled.

Source code in comicbox/readinglists/session.py
125
126
127
128
129
def check_cancelled(self) -> None:
    """Raise if the session was cancelled."""
    if self._cancelled.is_set():
        reason = "Reading-list fetch cancelled."
        raise OnlineLookupAbortedError(reason)

close()

Close the HTTP client and Metron’s shared sessions, if opened.

Comic Vine’s shared client is left open. Closing it closes its rate-limit buckets, which can fail a tagging lookup in the same process that holds one; OnlineSession.close releases it.

Source code in comicbox/readinglists/session.py
109
110
111
112
113
114
115
116
117
118
119
120
121
def close(self) -> None:
    """
    Close the HTTP client and Metron's shared sessions, if opened.

    Comic Vine's shared client is left open. Closing it closes its
    rate-limit buckets, which can fail a tagging lookup in the same
    process that holds one; ``OnlineSession.close`` releases it.
    """
    if self._http is not None:
        self._http.close()
        self._http = None
    if (metron := sys.modules.get(_METRON_SOURCE_MODULE)) is not None:
        metron.close_shared_sessions()

emit(event)

Hand an event to the caller’s handler, if any.

Source code in comicbox/readinglists/session.py
136
137
138
139
def emit(self, event: Event) -> None:
    """Hand an event to the caller's handler, if any."""
    if self._on_event is not None:
        self._on_event(event)

fetch_catalog(path, *, sha=None)

Fetch a list from the catalog by its path.

Paths change there; when path is gone and sha names the blob it had, the list with that sha is fetched in its place. The result’s source is of kind catalog, keyed by the path it was found at, with the blob sha as its revision.

Source code in comicbox/readinglists/session.py
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
def fetch_catalog(self, path: str, *, sha: str | None = None) -> ReadingListResult:
    """
    Fetch a list from the catalog by its path.

    Paths change there; when ``path`` is gone and ``sha`` names the
    blob it had, the list with that sha is fetched in its place. The
    result's source is of kind ``catalog``, keyed by the path it was
    found at, with the blob sha as its revision.
    """
    from comicbox.readinglists.sources.catalog import fetch_entry

    with self.fetching(SourceKind.CATALOG.value, path):
        data, source = fetch_entry(self, path, sha)
        self.check_cancelled()
        return self.load_fetched(data, source)

fetch_comicvine_arc(arc_id)

Fetch a Comic Vine story arc as an unordered list.

Comic Vine names an arc’s issues by id alone, so after the arc come its issues, a hundred a call, then their volumes the same way: an arc of N issues in V volumes costs 1 + ceil(N/100) + ceil(V/100) calls, each on its own hourly budget. Progress events count the issues as they arrive. A budget already spent fails the fetch at once, saying when it frees, rather than waiting.

Comic Vine has no conditional request, so there is no if_modified_since: compare the result’s source revision instead. Needs a Comic Vine API key. The result has no fmt.

Source code in comicbox/readinglists/session.py
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
def fetch_comicvine_arc(self, arc_id: int) -> ReadingListResult:
    """
    Fetch a Comic Vine story arc as an unordered list.

    Comic Vine names an arc's issues by id alone, so after the arc come
    its issues, a hundred a call, then their volumes the same way: an
    arc of N issues in V volumes costs ``1 + ceil(N/100) + ceil(V/100)``
    calls, each on its own hourly budget. Progress events count the
    issues as they arrive. A budget already spent fails the fetch at
    once, saying when it frees, rather than waiting.

    Comic Vine has no conditional request, so there is no
    ``if_modified_since``: compare the result's source revision instead.
    Needs a Comic Vine API key. The result has no ``fmt``.
    """
    from comicbox.readinglists.sources import comicvine

    comicvine.check_key(self)
    with self.fetching(SourceKind.COMICVINE_ARC.value, str(arc_id)):
        result = comicvine.fetch_arc(self, arc_id)
        self.check_cancelled()
        return result

fetch_metron_arc(arc_id, *, if_modified_since=None)

Fetch a Metron story arc as an unordered list.

Returns None, having fetched no issues, when the arc is unchanged since if_modified_since. Needs a Metron API token.

Source code in comicbox/readinglists/session.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
def fetch_metron_arc(
    self, arc_id: int, *, if_modified_since: datetime | None = None
) -> ReadingListResult | None:
    """
    Fetch a Metron story arc as an unordered list.

    Returns None, having fetched no issues, when the arc is unchanged
    since ``if_modified_since``. Needs a Metron API token.
    """
    from comicbox.readinglists.sources import metron

    metron.check_token(self)
    with self.fetching(SourceKind.METRON_ARC.value, str(arc_id)):
        result = metron.fetch_arc(self, arc_id, if_modified_since=if_modified_since)
        self.check_cancelled()
        return result

fetch_metron_list(list_id, *, if_modified_since=None)

Fetch a Metron reading list, in its order.

Returns None, having fetched no items, when the list is unchanged since if_modified_since. Progress events count the items as their pages arrive. Needs a Metron API token. The result has no fmt: it was read from no document.

Source code in comicbox/readinglists/session.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def fetch_metron_list(
    self, list_id: int, *, if_modified_since: datetime | None = None
) -> ReadingListResult | None:
    """
    Fetch a Metron reading list, in its order.

    Returns None, having fetched no items, when the list is unchanged
    since ``if_modified_since``. Progress events count the items as
    their pages arrive. Needs a Metron API token. The result has no
    ``fmt``: it was read from no document.
    """
    from comicbox.readinglists.sources import metron

    metron.check_token(self)
    with self.fetching(SourceKind.METRON_LIST.value, str(list_id)):
        result = metron.fetch_list(
            self, list_id, if_modified_since=if_modified_since
        )
        # A cancel during the last request still cancels.
        self.check_cancelled()
        return result

fetch_url(url)

Fetch a list from an http or https URL, in any format comicbox reads.

Redirects are followed and the download is capped at readinglists.max_download_bytes. Its source is of kind url. A user name and password in the URL are sent, and never recorded.

Source code in comicbox/readinglists/session.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def fetch_url(self, url: str) -> ReadingListResult:
    """
    Fetch a list from an http or https URL, in any format comicbox reads.

    Redirects are followed and the download is capped at
    ``readinglists.max_download_bytes``. Its source is of kind ``url``.
    A user name and password in the URL are sent, and never recorded.
    """
    from comicbox.readinglists.sources.url import fetch, without_userinfo

    kind = SourceKind.URL.value
    # A user name and password in the URL go with the request; they are
    # never recorded on the list, nor shown in an event or an error.
    shown = without_userinfo(url)
    with self.fetching(kind, shown):
        max_bytes = self._settings.readinglists.max_download_bytes
        data, revision = fetch(
            self.http(), url, max_bytes, cancelled=self._cancelled.is_set
        )
        self.check_cancelled()
        source = {
            SOURCE_KIND_KEY: kind,
            SOURCE_KEY_KEY: shown,
            SOURCE_URL_KEY: shown,
            SOURCE_REVISION_KEY: revision,
        }
        return self.load_fetched(data, source)

fetching(kind, key)

Bracket one fetch with its start and finish events.

Source code in comicbox/readinglists/session.py
154
155
156
157
158
159
160
161
162
@contextmanager
def fetching(self, kind: str, key: str) -> Generator[None]:
    """Bracket one fetch with its start and finish events."""
    self.check_cancelled()
    self.emit(ReadingListFetchStarted(source=kind, key=key))
    try:
        yield
    finally:
        self.emit(ReadingListFetchFinished(source=kind, key=key))

http()

Get the session’s HTTP client, built on first use.

Source code in comicbox/readinglists/session.py
141
142
143
144
145
146
147
148
149
150
151
152
def http(self) -> httpx.Client:
    """Get the session's HTTP client, built on first use."""
    if self._http is None:
        import httpx

        self._http = httpx.Client(
            follow_redirects=True,
            timeout=_TIMEOUT_SECONDS,
            headers={"User-Agent": user_agent()},
            transport=self._transport,
        )
    return self._http

load_fetched(data, source)

Read fetched bytes as a list from source, detecting the format.

A document that will not read names where it came from, as a file’s error names its path.

Source code in comicbox/readinglists/session.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def load_fetched(self, data: bytes, source: dict[str, Any]) -> ReadingListResult:
    """
    Read fetched bytes as a list from ``source``, detecting the format.

    A document that will not read names where it came from, as a
    file's error names its path.
    """
    try:
        result = loads(data)
    except ReadingListFormatError as exc:
        where = source.get(SOURCE_URL_KEY) or source.get(SOURCE_KEY_KEY)
        reason = f"{where}: {exc}"
        raise type(exc)(reason) from exc
    reading_list = attach_source(result.reading_list, source)
    return ReadingListResult(reading_list, result.fmt, result.warnings)

search_catalog(query)

Find the catalog’s lists whose path holds every word of query.

Source code in comicbox/readinglists/session.py
316
317
318
def search_catalog(self, query: str) -> tuple[CatalogEntry, ...]:
    """Find the catalog's lists whose path holds every word of ``query``."""
    return self.catalog().search(query)

search_metron(*, name=None, curator=None, username=None, modified_since=None)

Search Metron’s reading lists: public ones and the token’s own.

curator is a site Metron credits lists to, such as cbro. Needs a Metron API token.

Source code in comicbox/readinglists/session.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def search_metron(
    self,
    *,
    name: str | None = None,
    curator: str | None = None,
    username: str | None = None,
    modified_since: datetime | None = None,
) -> list[MetronListSummary]:
    """
    Search Metron's reading lists: public ones and the token's own.

    ``curator`` is a site Metron credits lists to, such as ``cbro``.
    Needs a Metron API token.
    """
    from comicbox.readinglists.sources import metron

    self.check_cancelled()
    found = metron.search(
        self,
        name=name,
        curator=curator,
        username=username,
        modified_since=modified_since,
    )
    self.check_cancelled()
    return found

Refused dataclass

A comic refused for missing entry position (from 0), and why.

Source code in comicbox/readinglists/match.py
111
112
113
114
115
116
117
@dataclass(frozen=True, slots=True)
class Refused:
    """A comic refused for missing entry ``position`` (from 0), and why."""

    position: int
    path: Path
    reason: RefusedReason

RefusedReason

Bases: StrEnum

Why a comic that looked like a missing entry was refused.

Source code in comicbox/readinglists/match.py
102
103
104
105
106
107
108
class RefusedReason(StrEnum):
    """Why a comic that looked like a missing entry was refused."""

    # It shares the entry's series, issue and cover year, of another volume.
    OTHER_VOLUME = "other-volume"
    # It shares a name key, and its cover year is more than a year off.
    COVER_YEAR = "cover-year"

SharedId dataclass

A database id the combined list holds on more than one entry.

No input repeats it, so it names one issue, but the rows that carry it could not all be joined: one input gave the issue twice, with a different id each time, and a row of one input joins at most one row of another. That is bad data worth showing. entries are the positions.

Source code in comicbox/readinglists/combine/__init__.py
81
82
83
84
85
86
87
88
89
90
91
92
93
94
@dataclass(frozen=True, slots=True)
class SharedId:
    """
    A database id the combined list holds on more than one entry.

    No input repeats it, so it names one issue, but the rows that carry it
    could not all be joined: one input gave the issue twice, with a
    different id each time, and a row of one input joins at most one row of
    another. That is bad data worth showing. ``entries`` are the positions.
    """

    source: str
    key: str
    entries: tuple[int, ...]

SmartListError

Bases: ReadingListFormatError

A ComicRack smart list.

Its <Matchers> are rules that select comics from a library, not a list of issues, so there is nothing to read.

Source code in comicbox/exceptions.py
148
149
150
151
152
153
154
class SmartListError(ReadingListFormatError):
    """
    A ComicRack smart list.

    Its ``<Matchers>`` are rules that select comics from a library, not a
    list of issues, so there is nothing to read.
    """

SourceKind

Bases: StrEnum

Where a list came from: the vocabulary of a source’s kind.

A source with a key and no revision is a pointer: the list is known to exist there and was not fetched from it.

Source code in comicbox/readinglists/schema.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
class SourceKind(StrEnum):
    """
    Where a list came from: the vocabulary of a source's ``kind``.

    A source with a ``key`` and no ``revision`` is a pointer: the list is
    known to exist there and was not fetched from it.
    """

    METRON_LIST = "metron-list"
    METRON_ARC = "metron-arc"
    COMICVINE_ARC = "comicvine-arc"
    # Keyed by the json-cbl file's UUID.
    JSON_CBL = "json-cbl"
    CATALOG = "catalog"
    URL = "url"
    FILE = "file"
    TAGS = "tags"

Verdict

Bases: StrEnum

What two lists are to each other, decided in this order.

Source code in comicbox/readinglists/compare.py
48
49
50
51
52
53
54
55
56
57
class Verdict(StrEnum):
    """What two lists are to each other, decided in this order."""

    # Each contains the other and the orders agree. Safe to combine.
    SAME = "same"
    # Each contains the other, in different orders: two takes on one event.
    VARIANT = "variant"
    # One contains the other, as tags do a curated list.
    SUBSET = "subset"
    UNRELATED = "unrelated"

arc_patch(list_name, number=None)

Build the patch that tags one comic as part of a list.

For write_metadata with merge_mode="additive", so the patch adds the arc and keeps the comic’s others; under update it would replace them.

Source code in comicbox/readinglists/arcs.py
192
193
194
195
196
197
198
199
200
201
def arc_patch(list_name: str, number: int | None = None) -> dict[str, Any]:
    """
    Build the patch that tags one comic as part of a list.

    For ``write_metadata`` with ``merge_mode="additive"``, so the patch adds
    the arc and keeps the comic's others; under ``update`` it would replace
    them.
    """
    arc = {} if number is None else {NUMBER_KEY: number}
    return {ARCS_KEY: {list_name: arc}}

detect_format(data)

Detect a reading list’s format by its content, not its file name.

XML by its root element; JSON and YAML by their top-level keys. JSON is tried before YAML, since every JSON document is also YAML.

Source code in comicbox/readinglists/registry.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def detect_format(data: str | bytes | bytearray) -> ReadingListFormats | None:
    """
    Detect a reading list's format by its content, not its file name.

    XML by its root element; JSON and YAML by their top-level keys. JSON is
    tried before YAML, since every JSON document is also YAML.
    """
    text = as_text(data)
    if not text.strip():
        return None
    if (root := xml_root(text)) is not None:
        return _XML_ROOTS.get(root)
    if (document := _parse_json(text)) is not None:
        return _match_signature(document, _JSON_SIGNATURES)
    return _match_signature(_parse_yaml(text), _YAML_SIGNATURES)

discriminators(entry)

Get what an entry tells its volume by.

Source code in comicbox/readinglists/identity.py
186
187
188
189
190
191
192
193
def discriminators(entry: Mapping[str, Any]) -> Discriminators:
    """Get what an entry tells its volume by."""
    series = entry.get(SERIES_KEY) or {}
    start_year = _whole_number(series.get(SERIES_START_YEAR_KEY))
    number = _whole_number((entry.get(VOLUME_KEY) or {}).get(NUMBER_KEY))
    if number is not None and number < YEAR_LIKE_VOLUME:
        return Discriminators(start_year, number)
    return Discriminators(number if start_year is None else start_year)

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)

entry_from_comic(metadata)

Build the entry that refers to a comic.

Takes {"comicbox": {...}} or the inner mapping, which is what a ReadResult’s tags holds. Keeps the series name, start year and ids, the volume number, the issue, the cover date and year, and the issue-level ids.

Source code in comicbox/readinglists/arcs.py
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def entry_from_comic(metadata: Mapping[str, Any]) -> dict[str, Any]:
    """
    Build the entry that refers to a comic.

    Takes ``{"comicbox": {...}}`` or the inner mapping, which is what a
    ``ReadResult``'s ``tags`` holds. Keeps the series name, start year and
    ids, the volume number, the issue, the cover date and year, and the
    issue-level ids.
    """
    comic = _comic(metadata)
    entry: dict[str, Any] = {}
    if series := _pick(comic.get(SERIES_KEY), _SERIES_KEYS):
        entry[SERIES_KEY] = series
    if volume := _pick(comic.get(VOLUME_KEY), (NUMBER_KEY,)):
        entry[VOLUME_KEY] = volume
    if issue := _pick(comic.get(ISSUE_KEY), _ISSUE_KEYS):
        entry[ISSUE_KEY] = issue
    if entry_date := _pick(comic.get(DATE_KEY), _DATE_KEYS):
        entry[DATE_KEY] = entry_date
    if identifiers := comic.get(IDENTIFIERS_KEY):
        entry[IDENTIFIERS_KEY] = _plain(identifiers)
    return entry

entry_keys(entry)

List the keys that identify an entry’s issue, strongest first.

("id", source, key) for each issue id, best ranked source first, then ("name", series, "year", year, number, suffix) by the start year or a year-like volume, then ("name", series, "volume", volume, number, suffix) by a volume number under 1900, then the weakest, ("name-year", series, cover year, number, suffix). Two entries are the same issue when they share a key and their discriminators do not conflict (Discriminators.conflicts): Z-Men (1963) and Z-Men (1991) may both be volume 1. An entry with none, no id and no series and issue with a start year, volume or cover year, matches nothing.

Source code in comicbox/readinglists/identity.py
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
def entry_keys(entry: Mapping[str, Any]) -> tuple[EntryKey, ...]:
    """
    List the keys that identify an entry's issue, strongest first.

    ``("id", source, key)`` for each issue id, best ranked source first,
    then ``("name", series, "year", year, number, suffix)`` by the start
    year or a year-like volume, then ``("name", series, "volume", volume,
    number, suffix)`` by a volume number under 1900, then the weakest,
    ``("name-year", series, cover year, number, suffix)``. Two entries are
    the same issue when they share a key and their discriminators do not
    conflict (``Discriminators.conflicts``): Z-Men (1963) and Z-Men (1991)
    may both be volume 1. An entry with none, no id and no series and issue
    with a start year, volume or cover year, matches nothing.
    """
    keys = [*_id_keys(entry), *_name_keys(entry)]
    if (name_year_key := _name_year_key(entry)) is not None:
        keys.append(name_year_key)
    return tuple(keys)

get_format(fmt)

Resolve a format token such as yaml, or pass a member through.

Source code in comicbox/readinglists/registry.py
62
63
64
65
66
67
68
69
70
def get_format(fmt: ReadingListFormats | str | None) -> ReadingListFormats:
    """Resolve a format token such as ``yaml``, or pass a member through."""
    if isinstance(fmt, ReadingListFormats):
        return fmt
    if isinstance(fmt, str) and (member := _TOKEN_MAP.get(fmt.strip().lower())):
        return member
    tokens = ", ".join(sorted(_TOKEN_MAP))
    reason = f"Unknown reading-list format {fmt!r}. Known formats: {tokens}."
    raise ReadingListFormatError(reason)

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)

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))

name_variants(entry)

List the series names to try for an entry, normalized, in order.

The name as given; the name without a trailing year or volume in parentheses (Bladehawk (2016), X (Vol. 2)), when it has one; the name without a leading article; and the name without a reprint suffix such as TPB or Omnibus. A year or volume is never added: Ivory Knight is not the series Ivory Knight 2020. For matching a list against comics only: entry_keys stays strict, so combine never joins on a variant.

Source code in comicbox/readinglists/identity.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
def name_variants(entry: Mapping[str, Any]) -> tuple[str, ...]:
    """
    List the series names to try for an entry, normalized, in order.

    The name as given; the name without a trailing year or volume in
    parentheses (``Bladehawk (2016)``, ``X (Vol. 2)``), when it has one; the
    name without a leading article; and the name without a reprint suffix
    such as TPB or Omnibus. A year or volume is never added: ``Ivory Knight``
    is not the series ``Ivory Knight 2020``. For matching a list against
    comics only: ``entry_keys`` stays strict, so ``combine`` never joins on
    a variant.
    """
    raw = str((entry.get(SERIES_KEY) or {}).get(NAME_KEY) or "").strip()
    if not raw:
        return ()
    normalized = [normalize_series(name) for name in _spelled_variants(raw)]
    normalized += [_without_reprint_suffix(name) for name in normalized]
    return tuple(dict.fromkeys(name for name in normalized if name))

normalize_series(name)

Normalize a series name for comparing.

Latin accents are dropped (Pokémon is pokemon), case is folded, a volume suffix is stripped, and every run of characters that are not letters or digits, in any script, becomes one space, so ワンピース keeps a name. Only the Combining Diacritical Marks block is dropped: other combining marks, such as kana voicing (ピ is not ヒ), are part of the letter and recompose with it. An ASCII name normalizes as lowercase letters and digits with single spaces between them.

Source code in comicbox/series_name.py
22
23
24
25
26
27
28
29
30
31
32
33
34
def normalize_series(name: str) -> str:
    """
    Normalize a series name for comparing.

    Latin accents are dropped (``Pokémon`` is ``pokemon``), case is folded,
    a volume suffix is stripped, and every run of characters that are not
    letters or digits, in any script, becomes one space, so ``ワンピース``
    keeps a name. Only the Combining Diacritical Marks block is dropped:
    other combining marks, such as kana voicing (``ピ`` is not ``ヒ``), are
    part of the letter and recompose with it. An ASCII name normalizes as
    lowercase letters and digits with single spaces between them.
    """
    return _spaced(_VOLUME_SUFFIX_RE.sub(" ", _folded(name)))

parse_issue(text)

Normalize an issue name and split it into its number and suffix.

The comicbox rules: #004AU is 4AU, number 4 and suffix AU; ½ is .5. 3 and 3.0 have equal numbers. -1 is a real issue number: IssueField.split_issue reads its sign.

Source code in comicbox/readinglists/identity.py
79
80
81
82
83
84
85
86
87
88
89
def parse_issue(text: Any) -> ParsedIssue:
    """
    Normalize an issue name and split it into its number and suffix.

    The comicbox rules: ``#004AU`` is ``4AU``, number 4 and suffix ``AU``;
    ``½`` is ``.5``. ``3`` and ``3.0`` have equal numbers. ``-1`` is a real
    issue number: ``IssueField.split_issue`` reads its sign.
    """
    name = IssueField.parse_issue(str(text).strip()) if text is not None else ""
    number_text, suffix = IssueField.split_issue(name)
    return ParsedIssue(name, _to_decimal(number_text), suffix.strip())

reading_lists_from_comics(comics)

Build one list per arc that a set of comics is tagged with.

Arc names group case-insensitively and keep the first spelling seen. Copies of one issue are one entry. Entries go by arc number, then cover date, series and issue. Lists come back sorted by name.

Source code in comicbox/readinglists/arcs.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
def reading_lists_from_comics(
    comics: Iterable[Mapping[str, Any]],
) -> list[dict[str, Any]]:
    """
    Build one list per arc that a set of comics is tagged with.

    Arc names group case-insensitively and keep the first spelling seen.
    Copies of one issue are one entry. Entries go by arc number, then cover
    date, series and issue. Lists come back sorted by name.
    """
    arcs: dict[str, _ArcMembers] = {}
    for metadata in comics:
        comic = _comic(metadata)
        if not (comic_arcs := comic.get(ARCS_KEY)):
            continue
        entry = entry_from_comic(comic)
        for name, arc in comic_arcs.items():
            members = arcs.setdefault(name.casefold(), _ArcMembers(name))
            members.add(entry, arc or {})
    return [arcs[folded].reading_list() for folded in sorted(arcs)]