Skip to content

comicbox.readinglists.render

Print reading lists, comparisons and combine reports for the CLI.

Every cell is a Text with a Style, never markup, and the consoles do not highlight: series names and paths carry brackets ([Marvel] Civil War) that markup would swallow or misread.

arc_text(name, number)

Name an arc and its number, as a line about it shows them.

Source code in comicbox/readinglists/render.py
442
443
444
def arc_text(name: str, number: int | None) -> str:
    """Name an arc and its number, as a line about it shows them."""
    return f"{name!r}" if number is None else f"{name!r} #{number}"

console(*, stderr=False)

Get a console that prints text as given.

Text is not wrapped: a long path stays on its line, and a terminal wraps it. A table fits a terminal’s width; written anywhere else, it is not wrapped at all, so each row stays one line for a script to read.

Source code in comicbox/readinglists/render.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def console(*, stderr: bool = False) -> Console:
    """
    Get a console that prints text as given.

    Text is not wrapped: a long path stays on its line, and a terminal
    wraps it. A table fits a terminal's width; written anywhere else, it is
    not wrapped at all, so each row stays one line for a script to read.
    """
    out = _Console(highlight=False, soft_wrap=True, stderr=stderr)
    if out.is_terminal:
        return out
    return _Console(
        highlight=False, soft_wrap=True, stderr=stderr, width=_UNWRAPPED_WIDTH
    )

entries_table(reading_list)

Tabulate a list’s entries in reading order.

Source code in comicbox/readinglists/render.py
149
150
151
152
153
154
155
156
def entries_table(reading_list: Mapping[str, Any]) -> Table:
    """Tabulate a list's entries in reading order."""
    table = Table(box=None, pad_edge=False)
    for column in ("#", "Series", "Year/Vol", "Issue", "Date", "Type", "Ids"):
        table.add_column(Text(column, style=_LABEL))
    for position, entry in enumerate(reading_list.get(ENTRIES_KEY) or (), start=1):
        table.add_row(*_entry_cells(position, entry))
    return table

header_table(reading_list)

Tabulate a list’s header.

Source code in comicbox/readinglists/render.py
198
199
200
201
202
203
204
205
def header_table(reading_list: Mapping[str, Any]) -> Table:
    """Tabulate a list's header."""
    table = Table(box=None, show_header=False, pad_edge=False)
    table.add_column(style=_LABEL)
    table.add_column()
    for label, value in _header_rows(reading_list):
        table.add_row(_text(label, _LABEL), _text(value))
    return table

print_ambiguous(out, path, position, volumes)

Say a comic is not tagged: its entry fits it and a comic of another volume.

Source code in comicbox/readinglists/render.py
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
def print_ambiguous(
    out: Console, path: Path, position: int, volumes: Sequence[int]
) -> None:
    """Say a comic is not tagged: its entry fits it and a comic of another volume."""
    kinds = []
    if any(value >= YEAR_LIKE_VOLUME for value in volumes):
        kinds.append("start year")
    if any(value < YEAR_LIKE_VOLUME for value in volumes):
        kinds.append("volume number")
    _failed_line(
        out,
        path,
        f"not written: entry #{position + 1} fits {volumes_text(volumes)}"
        f" alike; a {' or '.join(kinds)} on the entry settles it",
    )

print_arc_write(out, write, *, done, problem=None, moved=None, deleted=False, removed=None)

Print what tagging one file with an arc did, or would do, or why not.

problem says why a write that was made did not hold, moved is the CBZ a write converted the file to, and deleted whether the original then went. The file’s other paths follow, each on its own line, saying whether they went with it: removed gives each one removed, with why it could not be, if not.

Source code in comicbox/readinglists/render.py
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
def print_arc_write(
    out: Console,
    write: "ArcWrite",
    *,
    done: bool,
    problem: str | None = None,
    moved: Path | None = None,
    deleted: bool = False,
    removed: Mapping[Path, str | None] | None = None,
) -> None:
    """
    Print what tagging one file with an arc did, or would do, or why not.

    ``problem`` says why a write that was made did not hold, ``moved`` is
    the CBZ a write converted the file to, and ``deleted`` whether the
    original then went. The file's other paths follow, each on its own line,
    saying whether they went with it: ``removed`` gives each one removed,
    with why it could not be, if not.
    """
    change = write.change
    if change.action.value == "tagged":
        arc = arc_text(change.arc, change.number)
        _dim_line(out, change.path, f"already has {arc}; left alone")
    elif write.reason is not None:
        _failed_line(out, change.path, f"not written: {write.reason}")
    elif problem is not None:
        _failed_line(out, change.path, f"the write did not hold: {problem}")
    else:
        mark = Text("✓ ", style=_OK) if done else Text("· ", style=_DIM)
        out.print(
            Text.assemble(
                mark,
                (printable(str(change.path)), _PLAIN),
                (
                    printable(
                        " "
                        + _change_text(write, done=done, moved=moved, deleted=deleted)
                    ),
                    _DIM,
                ),
            )
        )
    _print_same_file(out, write, done=done, removed=removed or {})

print_catalog_entries(out, entries)

Tabulate catalog search results; fetch catalog:PATH takes the path.

Source code in comicbox/readinglists/render.py
337
338
339
340
341
342
def print_catalog_entries(out: Console, entries: "Sequence[CatalogEntry]") -> None:
    """Tabulate catalog search results; ``fetch catalog:PATH`` takes the path."""
    table = _results_table(("Curator", "Path"))
    for entry in entries:
        table.add_row(_text(entry.curator, _DIM), _text(entry.path))
    out.print(table)

print_combine_report(out, result, paths)

Print what each input added and every disagreement found.

Source code in comicbox/readinglists/render.py
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
def print_combine_report(
    out: Console, result: CombineResult, paths: Sequence[Path]
) -> None:
    """Print what each input added and every disagreement found."""
    reading_list = result.reading_list
    added = [0] * len(paths)
    for origins in result.provenance:
        added[origins[0].input_index] += 1
    for path, count in zip(paths, added, strict=True):
        noun = "entry" if count == 1 else "entries"
        out.print(
            Text.assemble(
                (printable(str(path)), _DIM), (f": {count} {noun} added", _PLAIN)
            )
        )
    for conflict in result.order_conflicts:
        message = (
            f"{_entry_label(reading_list, conflict.entry)}: {paths[conflict.input_index]}"
            f" puts it at row {conflict.row + 1}"
        )
        print_messages(out, (message,), "order")
    for conflict in result.id_conflicts:
        message = (
            f"{_entry_label(reading_list, conflict.entry)}: {conflict.source}"
            f" {conflict.kept} kept, {conflict.dropped} from"
            f" {paths[conflict.input_index]} row {conflict.row + 1}"
        )
        print_messages(out, (message,), "id")
    for index in result.name_joins:
        print_messages(out, (_entry_label(reading_list, index),), "joined by name only")
    for shared in result.shared_ids:
        positions = ", ".join(f"#{position + 1}" for position in shared.entries)
        message = f"{shared.source} {shared.key} is on entries {positions}"
        print_messages(out, (message,), "shared id")

print_comparison(out, comparison)

Print the verdict and the numbers behind it.

Source code in comicbox/readinglists/render.py
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
def print_comparison(out: Console, comparison: Comparison) -> None:
    """Print the verdict and the numbers behind it."""
    a_in_b, b_in_a = comparison.contains
    table = Table(box=None, show_header=False, pad_edge=False)
    table.add_column(style=_LABEL)
    table.add_column()
    rows = (
        ("Verdict", comparison.verdict.value),
        ("Overlap", f"{comparison.overlap:.2f}"),
        ("A in B", f"{a_in_b:.2f}"),
        ("B in A", f"{b_in_a:.2f}"),
        ("Order agreement", _order_text(comparison.order_agreement)),
    )
    for label, value in rows:
        table.add_row(
            _text(label, _LABEL), _text(value, _TITLE if label == "Verdict" else _PLAIN)
        )
    out.print(table)

print_error(out, path, error)

Print a failure in one line, naming its file once.

Source code in comicbox/readinglists/render.py
219
220
221
222
223
224
225
226
def print_error(out: Console, path: Path | str | None, error: BaseException) -> None:
    """Print a failure in one line, naming its file once."""
    message = str(error)
    if isinstance(error, OSError) and error.strerror:
        path = error.filename if error.filename is not None else path
        message = error.strerror
    prefix = f"{path}: " if path else ""
    out.print(Text.assemble((printable(prefix), _PLAIN), (printable(message), _ERROR)))

print_matches(out, reading_list, result, directory, notes=None)

Tabulate a list’s entries with the comics that are them, or missing.

Each comic is a row of its own, with how it matched and its note. A cover-year match of one of several volumes is marked ambiguous. Under a missing entry, each comic refused for it as another volume or for its cover year is a row marked refused.

Source code in comicbox/readinglists/render.py
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
def print_matches(
    out: Console,
    reading_list: Mapping[str, Any],
    result: "MatchResult",
    directory: Path,
    notes: Mapping[Path, str] | None = None,
) -> None:
    """
    Tabulate a list's entries with the comics that are them, or missing.

    Each comic is a row of its own, with how it matched and its note. A
    cover-year match of one of several volumes is marked ambiguous. Under a
    missing entry, each comic refused for it as another volume or for its
    cover year is a row marked ``refused``.
    """
    notes = notes or {}
    found = {match.position: match for match in result.found}
    refused: dict[int, list[Refused]] = {}
    for refusal in result.refused:
        refused.setdefault(refusal.position, []).append(refusal)
    table = _results_table(("#", "Series", "Year/Vol", "Issue", "Comic", "By"))
    for position, entry in enumerate(reading_list.get(ENTRIES_KEY) or ()):
        cells = _entry_cells(position + 1, entry)[:4]
        if (match := found.get(position)) is None:
            table.add_row(*cells, _text("missing", _WARN), _text(""))
            for refusal in refused.get(position, ()):
                shown = _refused_cell(refusal, directory, notes.get(refusal.path))
                table.add_row(*[_text("")] * len(cells), shown, _text("refused", _DIM))
            continue
        for comic in match.comics:
            shown = _comic_cell(comic, directory, notes.get(comic.path), match)
            table.add_row(*cells, shown, _text(comic.by.value, _DIM))
            cells = [_text("")] * len(cells)
    out.print(table)

print_messages(out, messages, label)

Print warnings or losses, one per line.

Source code in comicbox/readinglists/render.py
208
209
210
211
def print_messages(out: Console, messages: Sequence[str], label: str) -> None:
    """Print warnings or losses, one per line."""
    for message in messages:
        out.print(Text.assemble((f"{label}: ", _WARN), (printable(message), _PLAIN)))

print_metron_lists(out, lists)

Tabulate Metron search results; fetch metron:ID takes the ID.

Source code in comicbox/readinglists/render.py
322
323
324
325
326
327
328
329
330
331
332
333
334
def print_metron_lists(out: Console, lists: "Sequence[MetronListSummary]") -> None:
    """Tabulate Metron search results; ``fetch metron:ID`` takes the ID."""
    table = _results_table(("ID", "Name", "Type", "Curator", "User", "Modified"))
    for found in lists:
        table.add_row(
            _text(found.id),
            _text(f"{found.name} (private)" if found.private else found.name),
            _text(found.list_type),
            _text(found.curator),
            _text(found.username, _DIM),
            _text(found.modified.date(), _DIM),
        )
    out.print(table)

print_note(out, message)

Print a line about what is going on, dimmed.

Source code in comicbox/readinglists/render.py
214
215
216
def print_note(out: Console, message: str) -> None:
    """Print a line about what is going on, dimmed."""
    out.print(_text(message, _DIM))

print_reading_list(out, path, result)

Print a list’s name, header and entries.

Source code in comicbox/readinglists/render.py
229
230
231
232
233
234
235
236
def print_reading_list(out: Console, path: Path, result: ReadingListResult) -> None:
    """Print a list's name, header and entries."""
    label = f" ({result.fmt.value.label})" if result.fmt else ""
    out.print(_text(f"{path}{label}", _DIM))
    # The name on a line of its own: as a table title it wraps to the table.
    out.print(_text(result.reading_list.get(NAME_KEY) or "(unnamed)", _TITLE))
    out.print(header_table(result.reading_list))
    out.print(entries_table(result.reading_list))

print_status(out, path, ok, detail)

Print one line: a mark, the path and what was found.

Source code in comicbox/readinglists/render.py
239
240
241
242
243
244
245
246
def print_status(out: Console, path: Path | str, ok: bool, detail: str) -> None:  # noqa: FBT001
    """Print one line: a mark, the path and what was found."""
    mark = Text("✓ ", style=_OK) if ok else Text("✗ ", style=_ERROR)
    out.print(
        Text.assemble(
            mark, (printable(str(path)), _PLAIN), (printable(f" {detail}"), _DIM)
        )
    )

print_variant_only(out, path)

Say a comic was found only by a name variant, so is not tagged.

Source code in comicbox/readinglists/render.py
569
570
571
def print_variant_only(out: Console, path: Path) -> None:
    """Say a comic was found only by a name variant, so is not tagged."""
    _dim_line(out, path, "found only by a name variant; --variants tags it")

volumes_text(volumes)

Name the volumes an entry fits.

By start year, the 2011 and 2016 volumes, and by number, volumes 1 and 2.

Source code in comicbox/readinglists/render.py
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
def volumes_text(volumes: Sequence[int]) -> str:
    """
    Name the volumes an entry fits.

    By start year, ``the 2011 and 2016 volumes``, and by number,
    ``volumes 1 and 2``.
    """
    years = [str(value) for value in volumes if value >= YEAR_LIKE_VOLUME]
    numbers = [str(value) for value in volumes if value < YEAR_LIKE_VOLUME]
    parts = []
    if years:
        parts.append(f"the {_and(years)} volume{'s' if len(years) > 1 else ''}")
    if numbers:
        parts.append(f"volume{'s' if len(numbers) > 1 else ''} {_and(numbers)}")
    return " and ".join(parts)