Skip to content

comicbox.box.dump

Writing Methods.

ComicboxDump

Bases: ComicboxPages

Writing Methods.

Source code in comicbox/box/dump.py
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
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
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
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
class ComicboxDump(ComicboxPages):
    """Writing Methods."""

    def _get_keep_formats(self) -> frozenset[MetadataFormats]:
        """
        Get what a ``keep`` write writes: the formats named and those carried.

        A tag file the comic carries that did not parse refuses the write:
        what was read from the rest would be written without it.
        """
        carried = self.get_carried_formats()
        if carried.unreadable:
            names = ", ".join(carried.unreadable)
            reason = (
                f"Not writing {self._path}: its {names} could not be parsed,"
                " so keep cannot keep it."
            )
            raise UnparsedTagFileError(reason)
        return self._config.write.formats | carried.formats

    def get_write_formats(self) -> frozenset[MetadataFormats] | None:
        """
        Get the formats a write of this comic writes, as ``dump`` decides them.

        Under ``keep``, the formats named and every tag format the comic
        carries that was read. None when nothing is to be written.
        """
        return self._get_dump_formats()

    def _get_carried_formats_for_cbz(self) -> frozenset[MetadataFormats]:
        """
        Get the formats --cbz without -w writes back: those the archive carried.

        Its tag files, its ComicBookInfo comment and a PDF's own metadata;
        -m and --import values merge into them. Every loaded format was
        written, so -m added a comicbox-cli.yaml the comic never had.
        """
        carried = self.get_carried_formats().formats
        if not carried and self._has_given_metadata():
            logger.warning(
                f"{self._path} carries no tag format: without -w, the metadata"
                " given with -m or --import has nowhere to be written."
            )
        return carried

    def _has_given_metadata(self) -> bool:
        """Tell whether metadata came from -m, --import or the API caller."""
        general, convert = self._config.general, self._config.convert
        return bool(
            general.metadata_cli
            or convert.import_paths
            or self._sources.get(MetadataSources.API)
        )

    def _is_cbz_alone(self) -> bool:
        """Tell whether this is a --cbz write naming no format."""
        write = self._config.write
        return bool(
            self._config.convert.cbz
            and not write.formats
            and not write.keep_formats
            and not write.delete_all_tags
        )

    def _dump_carried_format(
        self,
        fmt: MetadataFormats,
        schema: Any,
        denormalized_metadata: Mapping,
        files: dict[str, Mapping],
        comment: dict[str, bytes | None],
    ) -> None:
        """
        Write a format --cbz carries over: a ComicBookInfo comment as a comment.

        It came back as a comic-book-info.json file. A tag file is written as
        any write writes it.
        """
        in_comment = self.get_carried_formats().in_comment
        if fmt in MetadataSources.ARCHIVE_COMMENT.value.formats and in_comment:
            comment["c"] = schema.dumps(denormalized_metadata).encode(errors="replace")
            filename = fmt.value.filename.lower()
            if not any(Path(name).name.lower() == filename for name in self.namelist()):
                return
        _dump_format(fmt, schema, denormalized_metadata, files, comment)

    def _get_dump_formats(self) -> frozenset[MetadataFormats] | None:
        write = self._config.write
        convert = self._config.convert
        formats: frozenset[MetadataFormats] | None = frozenset()
        if write.keep_formats:
            formats = self._get_keep_formats()
        elif write.formats:
            formats = write.formats
        elif convert.cbz:
            formats = self._get_carried_formats_for_cbz()
        elif not write.delete_all_tags:
            reason = "No formats specified to write"
            logger.warning(reason)
            formats = None
        else:
            reason = "Deleting all tags."
            logger.warning(reason)

        return formats

    def _ensure_pdf_to_cbz_default_format(
        self, formats: frozenset[MetadataFormats]
    ) -> frozenset[MetadataFormats]:
        """If no formats given to PDF -> CBZ convert default to ComicInfo."""
        if self._config.convert.cbz and self._defaults_to_comic_info():
            formats_without_pdf = formats - {MetadataFormats.PDF}
            if not formats_without_pdf:
                logger.info(
                    "PDF→CBZ conversion with no --write formats; "
                    "defaulting to ComicInfo."
                )
                formats = frozenset(formats_without_pdf | {MetadataFormats.COMIC_INFO})
        return formats

    def _defaults_to_comic_info(self) -> bool:
        """
        Whether the PDF to CBZ default may add ComicInfo.

        Only for a PDF: an untagged comic of any other kind gains no tag file
        from --cbz. Under keep, also never over a ComicInfo the archive
        carries and the read configuration did not read: keep replaces no
        tag file it did not read.
        """
        if not self._archive_is_pdf:
            return False
        if not self._config.write.keep_formats:
            return True
        unread = MetadataFormats.COMIC_INFO not in self.get_carried_formats().formats
        filename = MetadataFormats.COMIC_INFO.value.filename.lower()
        return not (
            unread
            and any(Path(name).name.lower() == filename for name in self.namelist())
        )

    def _dump_format_to_archive(
        self,
        fmt: MetadataFormats,
        files: dict[str, Mapping],
        pdf_md: dict,
        comment: dict[str, bytes | None],
    ) -> None:
        if fmt not in _WRITABLE_FORMATS:
            # -w pdf returned here, never reaching the PDF branch below.
            return

        (
            schema,
            denormalized_metadata,
        ) = self._to_dict(fmt)
        if not denormalized_metadata:
            return
        if fmt == MetadataFormats.PDF and not self._config.convert.cbz:
            # fmt is PDF here, so the pair above is already the PDF pair.
            mupdf_md = schema.dump(denormalized_metadata) or {}
            if isinstance(mupdf_md, Mapping):
                pdf_md.update(mupdf_md.get(schema.ROOT_TAG, {}))
        elif self._config.write.keep_formats:
            self._dump_kept_format(fmt, schema, denormalized_metadata, files, comment)
        elif self._is_cbz_alone():
            self._dump_carried_format(
                fmt, schema, denormalized_metadata, files, comment
            )
        else:
            _dump_format(fmt, schema, denormalized_metadata, files, comment)

    def _dump_kept_format(
        self,
        fmt: MetadataFormats,
        schema: Any,
        denormalized_metadata: Mapping,
        files: dict[str, Mapping],
        comment: dict[str, bytes | None],
    ) -> None:
        """
        Write a format under keep wherever the comic carries it.

        A ComicBookInfo comment stays a comment, and a file is written back
        at every member path that bears its name, read or not: the write
        removes each of them, and no copy may be left stale to win the next
        read. A format the comic does not carry is written as any write
        writes it.
        """
        written = False
        in_comment = self.get_carried_formats().in_comment
        if fmt in MetadataSources.ARCHIVE_COMMENT.value.formats and in_comment:
            comment["c"] = schema.dumps(denormalized_metadata).encode(errors="replace")
            written = True
        filename = fmt.value.filename.lower()
        for path in self.namelist():
            if Path(path).name.lower() != filename:
                continue
            files[path] = schema.dumps(
                _without_filename_only_keys(schema, denormalized_metadata)
            )
            written = True
        if not written:
            _dump_format(fmt, schema, denormalized_metadata, files, comment)

    def _dump_to_archive(self, formats: frozenset[MetadataFormats]) -> None:
        """Prepare archive files and comment and write to archive."""
        self._warn_of_unparsed_tag_files(formats)
        files = {}
        comment: dict[str, bytes | None] = {"c": self._comment_left_by_write()}
        pdf_md = {}
        if not self._config.write.delete_all_tags:
            formats = self._ensure_pdf_to_cbz_default_format(formats)
            # In one fixed order: a frozenset's follows the hash seed.
            for fmt in sorted(formats, key=_FORMAT_ORDER.__getitem__):
                self._dump_format_to_archive(fmt, files, pdf_md, comment)

        if self._writes_pdf_metadata(formats):
            # pymupdf leaves a key it is not given: an empty value clears it.
            pdf_md = {**_CLEARED_PDF_METADATA, **pdf_md}
        # write to the archive, then re-seed caches from the new bytes.
        self.write_archive_metadata(files, comment["c"], pdf_md)
        self._reset_caches_after_write()

    def _comment_left_by_write(self) -> bytes | None:
        """
        Get the archive comment a write leaves unless a format rewrites it.

        None leaves the comment as it is, and b"" clears it. Keep leaves
        it. Otherwise a ComicBookInfo comment is a tag format, removed like
        any other the write does not name, while free text, such as a
        scanner's note, is not one and is left. --delete-all-tags clears
        either.
        """
        write = self._config.write
        if write.keep_formats:
            return None
        if write.delete_all_tags:
            return b""
        comment = self._get_comment()
        return None if comment and not is_comic_book_info(comment) else b""

    def _writes_pdf_metadata(self, formats: frozenset[MetadataFormats]) -> bool:
        """
        Tell whether this write sets a PDF's own metadata in place.

        It does under -w pdf, and under keep for a PDF that has some; and
        --delete-all-tags clears it. A field it maps that the metadata no
        longer has is then cleared, as a zip write drops a tag file.
        """
        if not self._archive_is_pdf or self._config.convert.cbz:
            return False
        return self._config.write.delete_all_tags or MetadataFormats.PDF in formats

    def _reset_caches_after_write(self) -> None:
        """
        Re-seed the box caches from the now-rewritten archive.

        Everything parsed from the old archive bytes is stale after a
        write, but the sources that never came from the file can't be
        rebuilt by re-reading it: the caller-injected API metadata, and
        whatever the online lookup fetched. The lookup is once-per-box
        (``_online_lookup_done_flag`` outlives this reset), so dropping
        its sources here left the post-write rename — and any other
        read after a write — deciding on pre-online metadata, minus
        whatever the written formats happened to carry back.

        Lives here rather than in the archive write layer so file I/O
        stays decoupled from the source-cache lifecycle.
        """
        keep_sources = {
            source: source_data_list
            for source in self.SOURCES_SET_ELSEWHERE
            if (source_data_list := self._sources.get(source))
        }
        self._reset_archive(None, None, keep_sources)

    def _is_write_disabled(self) -> bool:
        """Return whether the config asks for no write at all."""
        write = self._config.write
        return self._config.general.dry_run or not (
            write.formats
            or write.keep_formats
            or self._config.convert.cbz
            or write.delete_all_tags
        )

    def _can_hold(self, fmt: MetadataFormats) -> bool:
        """Tell whether this write can put a format into the archive."""
        if fmt in ARCHIVE_FORMATS:
            return True
        return (
            fmt == MetadataFormats.PDF
            and self._archive_is_pdf
            and not self._config.convert.cbz
        )

    def _refuse_formats_it_cannot_hold(self) -> None:
        """
        Refuse -w naming no format this archive can hold; warn of any it names.

        -w removes the tag formats it does not name, so -w pdf on a CBZ
        removed every tag file and wrote none: a PDF's own metadata cannot go
        into a zip, nor the file name or an online source's into any
        archive. A PDF converted to a CBZ gets its ComicInfo default instead.
        Under keep the carried formats are written whatever -w names.
        """
        write = self._config.write
        if not write.formats or write.delete_all_tags or self._pdf_default_applies():
            return
        cannot = sorted(
            fmt.value.label for fmt in write.formats if not self._can_hold(fmt)
        )
        if not cannot:
            return
        kind = self._written_kind()
        if len(cannot) == len(write.formats) and not write.keep_formats:
            reason = (
                f"{self._path}: -w names no format a {kind} can hold"
                f" ({', '.join(cannot)}), so nothing was written."
            )
            raise UnwritableFormatError(reason)
        logger.warning(
            f"{self._path}: a {kind} cannot hold {', '.join(cannot)}; not written."
        )

    def _pdf_default_applies(self) -> bool:
        """Tell whether a PDF converted to a CBZ gets ComicInfo for what -w names."""
        return bool(
            self._config.convert.cbz
            and self._defaults_to_comic_info()
            and not self._config.write.formats - {MetadataFormats.PDF}
        )

    def _written_kind(self) -> str:
        """Name the kind of archive the write puts its tags into."""
        if self._config.convert.cbz:
            return FileTypeEnum.CBZ.value
        return self._file_type.value if self._file_type else "comic"

    def dump(self, formats: frozenset[MetadataFormats] | None = None) -> None:
        """Write metadata according to config.write settings."""
        if self._is_write_disabled():
            logger.info(f"Not writing metadata for: {self._path}")
            return None
        # Before the destination is checked, so --cbz converts nothing.
        self._refuse_formats_it_cannot_hold()

        if self._path:
            # Refuse an occupied conversion destination before any metadata
            # is read. _get_dump_formats() below loads and merges every
            # source, which is the expensive part of a write that was only
            # ever going to be refused -- a kept-original CBR whose CBZ twin
            # already exists is the common case, and it reaches here from
            # the CLI as well as the API. _create_zipfile repeats the check
            # (it is idempotent) so direct callers stay guarded.
            self._get_new_archive_path()

        # Must get metadata *before* get write formats
        if formats is None:
            formats = self._get_dump_formats()
            if formats is None:
                return None
        return self._write_formats(formats)

    def _write_formats(self, formats: frozenset[MetadataFormats]) -> None:
        """Write the formats decided, or say there is nothing to keep."""
        write = self._config.write
        writes = bool(formats or self._config.convert.cbz or write.delete_all_tags)
        if write.keep_formats and not writes:
            # Not a failure: there is just nothing to keep, and none named.
            logger.info(f"Nothing to keep in {self._path}: not writing it.")
            return None
        result = self._dump_to_archive(formats) if writes else None
        logger.info(f"Wrote metadata to: {self._path}")
        if formats and self._is_cbz_alone():
            self._warn_of_unwritten_patch_values()
        return result

    def _given_metadata(self) -> dict:
        """Merge the -m and --import values, as a read merges them."""
        merged: dict = {}
        for source in _GIVEN_SOURCES:
            for loaded in self.get_normalized_metadata(source) or ():
                merge_source(
                    merged, dict(loaded.metadata.get(ROOT_TAG) or {}), AdditiveMerger
                )
        return merged

    def _read_back(self) -> Mapping[str, Any]:
        """
        Read the written comic as a plain read does, without -m or --import.

        Its own sources merged and computed, so a value the reader derives,
        such as the identifiers ComicInfo carries in its Notes and Web, is
        there as the reader has it.
        """
        config = self._config
        plain = replace(
            config,
            general=replace(config.general, metadata_cli=None),
            convert=replace(config.convert, import_paths=(), cbz=False),
        )
        with type(self)(self._path, config=plain) as reader:
            return reader.get_internal_metadata().get(ROOT_TAG) or {}

    def _stamped_keys(self) -> frozenset[str]:
        """Name the keys the stamp rewrote: they have a place, if not -m's value."""
        keys = {TAGGER_KEY, UPDATED_AT_KEY}
        if self._config.write.stamp_notes:
            keys.add(NOTES_KEY)
        return frozenset(keys)

    def _warn_of_unwritten_patch_values(self) -> None:
        """
        Name the -m and --import keys a --cbz without -w had nowhere to write.

        Their values go only into the formats the comic carried, and a format
        can have no place for one: MetronInfo for a title apart from its
        stories, CoMet for tags. What the comic reads back after the write
        shows which landed; -w names a format that holds the rest.
        """
        given = self._given_metadata()
        if not given:
            return
        held = self._read_back()
        stamped = self._stamped_keys()
        if missing := sorted(
            key
            for key, value in given.items()
            if key not in stamped and not _holds_given(key, value, held)
        ):
            logger.warning(
                f"{self._path}: the formats it carries have no place for"
                f" {', '.join(missing)} from -m or --import, so they were not"
                " written. Name a format that holds them with -w."
            )

    def _warn_of_unparsed_tag_files(self, formats: frozenset[MetadataFormats]) -> None:
        """
        Name each tag file that did not parse and that this write takes away.

        Without keep, a write replaces or removes every tag file the comic
        has; one that could not be parsed added nothing to what is written.
        Keep refuses such a comic instead, and deleting all tags means it.
        """
        write = self._config.write
        if write.keep_formats or write.delete_all_tags:
            return
        written = {fmt.value.filename.lower() for fmt in formats}
        for name in self.get_carried_formats().unreadable:
            if name.lower() not in ALL_ARCHIVE_METADATA_FILENAMES:
                continue
            if name.lower() in written:
                why = "so nothing it held is in the new one"
                logger.warning(f"Replacing {name} in {self._path}: {_UNPARSED}, {why}.")
            else:
                why = "and its format is not one written"
                logger.warning(
                    f"Removing {name} from {self._path}: {_UNPARSED}, {why}."
                )

dump(formats=None)

Write metadata according to config.write settings.

Source code in comicbox/box/dump.py
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
def dump(self, formats: frozenset[MetadataFormats] | None = None) -> None:
    """Write metadata according to config.write settings."""
    if self._is_write_disabled():
        logger.info(f"Not writing metadata for: {self._path}")
        return None
    # Before the destination is checked, so --cbz converts nothing.
    self._refuse_formats_it_cannot_hold()

    if self._path:
        # Refuse an occupied conversion destination before any metadata
        # is read. _get_dump_formats() below loads and merges every
        # source, which is the expensive part of a write that was only
        # ever going to be refused -- a kept-original CBR whose CBZ twin
        # already exists is the common case, and it reaches here from
        # the CLI as well as the API. _create_zipfile repeats the check
        # (it is idempotent) so direct callers stay guarded.
        self._get_new_archive_path()

    # Must get metadata *before* get write formats
    if formats is None:
        formats = self._get_dump_formats()
        if formats is None:
            return None
    return self._write_formats(formats)

get_write_formats()

Get the formats a write of this comic writes, as dump decides them.

Under keep, the formats named and every tag format the comic carries that was read. None when nothing is to be written.

Source code in comicbox/box/dump.py
153
154
155
156
157
158
159
160
def get_write_formats(self) -> frozenset[MetadataFormats] | None:
    """
    Get the formats a write of this comic writes, as ``dump`` decides them.

    Under ``keep``, the formats named and every tag format the comic
    carries that was read. None when nothing is to be written.
    """
    return self._get_dump_formats()