Skip to content

comicbox.write ¶

Public write API: single-file write_metadata and batch bulk_write.

Wraps the existing Comicbox(...).dump() plumbing with a documented, Codex-facing surface:

  • merge_mode: "additive" / "update" / "replace" — picks the merge strategy applied to the patch dict against the comic’s existing metadata. None (the default) defers to the config’s write.merge_mode, itself additive unless a config file or --merge-mode says otherwise. See :class:comicbox.config.settings.MergeMode.
  • formats: which on-archive formats to write back (ComicInfo.xml, comicbox.yaml, …). Names match the MetadataFormats enum value.
  • delete_keys: glom key paths removed from the final metadata before writing. Merging can only add or replace — an empty patch value is pruned by the schema, so this is the only way a write can clear an existing field.
  • dry_run: return the would-be-written payload instead of touching the archive.

bulk_write orchestrates the same call over many files via a process- global ThreadPoolExecutor (writes are I/O bound — full archive repack per CBZ). A module-level semaphore caps concurrent writes so a big batch can’t starve other disk traffic.

BulkWriteItem dataclass ¶

One unit of work for bulk_write.

Source code in comicbox/write.py
119
120
121
122
123
124
125
126
127
128
@dataclass(frozen=True, slots=True)
class BulkWriteItem:
    """One unit of work for ``bulk_write``."""

    path: Path
    patch: Mapping[str, Any]
    # None defers to the base config's write.merge_mode (default: additive).
    merge_mode: Mode | None = None
    formats: frozenset[FormatName] | None = None
    delete_keys: frozenset[str] | None = None

WriteResult dataclass ¶

Per-file outcome of a write.

Source code in comicbox/write.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
@dataclass(frozen=True, slots=True)
class WriteResult:
    """Per-file outcome of a write."""

    path: Path
    written: bool = False
    dry_run_payload: dict[str, str] | None = None
    error: BaseException | None = None
    # True when the batch was cancelled before this file's write started
    # (stop_on_error tripped, or the caller set the cancel event).
    cancelled: bool = False
    # On-disk path after a successful write. Differs from ``path`` when the
    # write converted the archive to CBZ (CBR/CBT/CB7 sources are unwritable,
    # so a write repacks them; the original survives alongside the new CBZ
    # unless the config sets ``general.delete_orig``). None for dry runs,
    # errors, and cancellations, which leave the archive untouched.
    final_path: Path | None = None

bulk_write(items, *, workers=None, on_event=None, stop_on_error=False, cancel=None, base_config=None, preflight=True) ¶

Write metadata to many files in parallel.

Returns an iterator that MUST be drained: writes are submitted in a bounded window as results are consumed, so discarding the iterator without iterating performs no writes. Input handling, the BatchStarted event, and pool creation happen eagerly at call time. Abandoning the iterator midway never blocks: queued writes are cancelled and in-flight ones finish in their worker threads.

Yields :class:WriteResult per file in completion order, not submission order. Caller may pass a cancel :class:threading.Event; once set, no new writes start: in-flight writes run to completion and every queued file is reported with cancelled=True. With stop_on_error=True the first failed write trips the same cancellation (an internal event is created if the caller didn’t pass one). on_event receives the shared :class:comicbox.events stream (BatchStarted / FileParsed / FileError / BatchFinished); cancelled files emit no per-file event.

preflight (default on) sniffs every destination before any archive is written, on the first next() rather than at call time. It refuses a batch’s collisions up front – a destination already on disk, and two archives converging on one name – so a batch fails fast instead of repacking an archive and refusing it at the end, and the loser of an in-batch collision is decided by submission order rather than by thread race. It also fails an unreadable or unsupported file here, with the sniff’s own error. preflight=False restores the pre-5.2.0 behavior. The write path’s own destination claim stays either way, as the backstop for concurrent callers: two bulk_write calls in one process see each other only through it.

Source code in comicbox/write.py
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
def bulk_write(
    items: Iterable[BulkWriteItem],
    *,
    workers: int | None = None,
    on_event: EventHandler | None = None,
    stop_on_error: bool = False,
    cancel: threading.Event | None = None,
    base_config: ComicboxSettings | None = None,
    preflight: bool = True,
) -> Generator[WriteResult, None, None]:
    """
    Write metadata to many files in parallel.

    Returns an iterator that MUST be drained: writes are submitted in a
    bounded window as results are consumed, so discarding the iterator
    without iterating performs no writes. Input handling, the
    ``BatchStarted`` event, and pool creation happen eagerly at call
    time. Abandoning the iterator midway never blocks: queued writes are
    cancelled and in-flight ones finish in their worker threads.

    Yields :class:`WriteResult` per file in *completion* order, not
    submission order. Caller may pass a ``cancel`` :class:`threading.Event`;
    once set, no new writes start: in-flight writes run to completion and
    every queued file is reported with ``cancelled=True``. With
    ``stop_on_error=True`` the first failed write trips the same
    cancellation (an internal event is created if the caller didn't pass
    one). ``on_event`` receives the shared :class:`comicbox.events`
    stream (``BatchStarted`` / ``FileParsed`` / ``FileError`` /
    ``BatchFinished``); cancelled files emit no per-file event.

    ``preflight`` (default on) sniffs every destination before any
    archive is written, on the first ``next()`` rather than at call
    time. It refuses a batch's collisions up front -- a destination
    already on disk, and two archives converging on one name -- so a
    batch fails fast instead of repacking an archive and refusing it at
    the end, and the loser of an in-batch collision is decided by
    submission order rather than by thread race. It also fails an
    unreadable or unsupported file here, with the sniff's own error.
    ``preflight=False`` restores the pre-5.2.0 behavior. The write path's
    own destination claim stays either way, as the backstop for
    *concurrent callers*: two ``bulk_write`` calls in one process see
    each other only through it.
    """
    item_list = list(items)
    total = len(item_list)
    if stop_on_error and cancel is None:
        # stop_on_error signals through the cancel event; make one if the
        # caller didn't supply their own.
        cancel = threading.Event()
    if on_event is not None:
        on_event(BatchStarted(total=total))
    # Eager pool creation; its threads only spawn on first submit, so a
    # never-iterated iterator leaks nothing.
    pool = ThreadPoolExecutor(max_workers=workers)
    # Submission window matches the pool width so the pool stays saturated
    # while no item waits in the pool's internal queue beyond cancel's reach.
    options = _BatchOptions(
        window=workers or _MAX_CONCURRENT_WRITES,
        base_config=base_config,
        total=total,
        on_event=on_event,
        stop_on_error=stop_on_error,
        cancel=cancel,
        preflight=preflight,
    )
    return _drain_bulk_write(pool, item_list, options)

write_metadata(path, patch, *, merge_mode=None, formats=None, delete_keys=None, dry_run=False, base_config=None) ¶

Write metadata to one comic archive.

patch is a comicbox-shaped dict — either the contents under the "comicbox" root tag, or the root-wrapped form Comicbox.to_dict returns ({"comicbox": {...}}); the wrapper is detected and unwrapped so the natural round-trip works.

merge_mode selects how the patch overlays the comic’s existing tags: "additive" (dicts recurse, lists concatenate), "replace" (dicts recurse, lists overwrite) or "update" (top level keys replaced wholesale, siblings of a patched key dropped). None defers to the config’s write.merge_mode; an explicit value always wins. See :class:comicbox.config.settings.MergeMode.

delete_keys are glom key paths (relative to the root tag, e.g. "summary" or "series.name") removed from the final merged metadata before serialization — the only way a write can clear an existing field, since empty patch values are pruned on schema load and merging never removes. They are layered onto the config’s general.delete_keys; unknown keys are ignored. The patch may be empty when delete_keys is non-empty (a pure-clear write).

formats may include "keep": the write then removes no tag format the comic already carries, and writes the ones it read back beside those named, so ["keep"] alone rewrites what the comic has. A comic with nothing to keep and none named is not written, without an error.

With dry_run=True no archive is touched; the result’s dry_run_payload carries the serialized would-be-written content per format written (keyed by format name).

Source code in comicbox/write.py
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
def write_metadata(
    path: Path,
    patch: Mapping[str, Any],
    *,
    merge_mode: Mode | None = None,
    formats: Iterable[FormatName] | None = None,
    delete_keys: Iterable[str] | None = None,
    dry_run: bool = False,
    base_config: ComicboxSettings | None = None,
) -> WriteResult:
    """
    Write metadata to one comic archive.

    ``patch`` is a comicbox-shaped dict — either the contents *under* the
    ``"comicbox"`` root tag, or the root-wrapped form ``Comicbox.to_dict``
    returns (``{"comicbox": {...}}``); the wrapper is detected and
    unwrapped so the natural round-trip works.

    ``merge_mode`` selects how the patch overlays the comic's existing
    tags: ``"additive"`` (dicts recurse, lists concatenate),
    ``"replace"`` (dicts recurse, lists overwrite) or ``"update"``
    (top level keys replaced wholesale, siblings of a patched key
    dropped). ``None`` defers to the config's ``write.merge_mode``; an
    explicit value always wins. See
    :class:`comicbox.config.settings.MergeMode`.

    ``delete_keys`` are glom key paths (relative to the root tag, e.g.
    ``"summary"`` or ``"series.name"``) removed from the final merged
    metadata before serialization — the only way a write can *clear* an
    existing field, since empty patch values are pruned on schema load
    and merging never removes. They are layered onto the config's
    ``general.delete_keys``; unknown keys are ignored. The patch may be
    empty when ``delete_keys`` is non-empty (a pure-clear write).

    ``formats`` may include ``"keep"``: the write then removes no tag
    format the comic already carries, and writes the ones it read back
    beside those named, so ``["keep"]`` alone rewrites what the comic has.
    A comic with nothing to keep and none named is not written, without
    an error.

    With ``dry_run=True`` no archive is touched; the result's
    ``dry_run_payload`` carries the serialized would-be-written content
    per format written (keyed by format name).
    """
    patch = _unwrap_root_tag(patch) if patch else {}
    delete_key_set = _normalize_delete_keys(delete_keys)
    if not patch and not delete_key_set:
        msg = (
            "write_metadata(): patch must be a non-empty mapping"
            " unless delete_keys is non-empty"
        )
        raise WriteValidationError(msg)
    mode_enum = _validate_merge_mode(merge_mode) if merge_mode is not None else None
    fmt_set, keep = _resolve_formats(formats)
    settings = _build_write_settings(
        mode_enum,
        fmt_set,
        delete_keys=delete_key_set,
        base_config=base_config,
        keep=keep,
    )
    # A delete-only write passes no API metadata; the archive's own
    # sources minus delete_keys are what gets rewritten.
    wrapped: dict[str, Any] | None = (
        {ComicboxSchemaMixin.ROOT_TAG: dict(patch)} if patch else None
    )

    try:
        return _write_comic(
            path, settings, wrapped, fmt_set, keep=keep, dry_run=dry_run
        )
    except Exception as exc:
        return WriteResult(path=path, error=exc)