Skip to content

comicbox.readinglists.sources.catalog ¶

The DieselTech catalog: an index of a GitHub repository of .cbl lists.

The repository has no index, so one is built from a single recursive git-tree call to GitHub’s API and cached under the online cache directory with its ETag. Within readinglists.catalog_ttl the cached index is used without a request; after it, the ETag revalidates it. Lists download from raw.githubusercontent.com, which GitHub’s API rate limit does not cover.

Paths are not stable there, so a list is known by its path and its blob sha: when a path is gone, the entry with the same sha is taken in its place.

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.

curator(path) ¶

Read a list’s curator from its file name, else its innermost folder.

Source code in comicbox/readinglists/sources/catalog.py
177
178
179
180
181
182
183
184
185
186
187
188
189
def curator(path: str) -> str | None:
    """Read a list's curator from its file name, else its innermost folder."""
    parts = PurePosixPath(path)
    if (match := _TRAILING_GROUP_RE.search(parts.stem)) and (
        mark := _CURATOR_MARKS.get(match.group(1).strip().casefold())
    ):
        return mark
    for folder in reversed(parts.parent.parts):
        folded = folder.casefold()
        for name, mark in _CURATOR_MARKS.items():
            if folded == name or folded.startswith(f"{name} "):
                return mark
    return None

entries_from_tree(items) ¶

Index the .cbl blobs of a git tree, in path order.

Source code in comicbox/readinglists/sources/catalog.py
205
206
207
208
209
210
211
212
def entries_from_tree(items: Iterable[Mapping[str, Any]]) -> tuple[CatalogEntry, ...]:
    """Index the ``.cbl`` blobs of a git tree, in path order."""
    lists = (
        item
        for item in items
        if item.get("type") == "blob" and str(item.get("path", "")).endswith(_SUFFIX)
    )
    return tuple(sorted((_entry(item) for item in lists), key=lambda e: e.path))

fetch_entry(context, path, sha=None) ¶

Download a list by path, or by sha when the path is gone.

A cached index may predate a rename: when the list is missing from it, or its path no longer downloads, the index is fetched again once and the list looked up anew.

Source code in comicbox/readinglists/sources/catalog.py
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
def fetch_entry(
    context: FetchContext, path: str, sha: str | None = None
) -> tuple[bytes, dict[str, Any]]:
    """
    Download a list by path, or by sha when the path is gone.

    A cached index may predate a rename: when the list is missing from it,
    or its path no longer downloads, the index is fetched again once and
    the list looked up anew.
    """
    catalog, asked = load_catalog(context)
    if (entry := catalog.find(path, sha)) is not None:
        try:
            return _download(context, catalog, entry)
        except HttpStatusError as exc:
            if asked or exc.status != HTTPStatus.NOT_FOUND:
                raise
    if not asked:
        catalog, _ = load_catalog(context, refresh=True)
        entry = catalog.find(path, sha)
    if entry is None:
        reason = f"{path} is not in the catalog of {catalog.repo} at {catalog.ref}."
        raise ReadingListFetchError(reason)
    context.check_cancelled()
    return _download(context, catalog, entry)

load_catalog(context, *, refresh=False) ¶

Get the index; say whether GitHub was asked for it just now.

refresh asks GitHub even within the cache lifetime, as cache mode refresh does.

Source code in comicbox/readinglists/sources/catalog.py
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
def load_catalog(
    context: FetchContext, *, refresh: bool = False
) -> tuple[Catalog, bool]:
    """
    Get the index; say whether GitHub was asked for it just now.

    ``refresh`` asks GitHub even within the cache lifetime, as cache mode
    ``refresh`` does.
    """
    repo, ref = _repo_and_ref(context)
    path = _cache_path(context, repo, ref)
    cached = _read_cache(path, repo, ref)
    refresh = refresh or context.settings.online.cache.mode is CacheMode.REFRESH
    lifetime = context.settings.readinglists.catalog_ttl
    if (
        cached is not None
        and not refresh
        and datetime.now(tz=UTC) - cached.fetched < lifetime
    ):
        return cached, False
    context.check_cancelled()
    catalog = _fetch_tree(context, repo, ref, cached)
    _write_cache(path, catalog)
    return catalog, True