Skip to content

comicbox.box.dump_files

Special file writes.

ComicboxDumpToFiles

Bases: ComicboxDump

Special file writes.

Source code in comicbox/box/dump_files.py
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 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
class ComicboxDumpToFiles(ComicboxDump):
    """Special file writes."""

    def to_file(
        self,
        dest_path: Path | str | None = None,
        fmt: MetadataFormats = MetadataFormats.COMICBOX_JSON,
        **kwargs: Any,
    ) -> None:
        """Export metadatat to a file with a schema."""
        if dest_path is None:
            dest_path = self._config.general.dest_path
        dest_path = Path(dest_path)
        fn = fmt.value.filename
        path = dest_path / fn
        if not path.resolve().is_relative_to(dest_path.resolve()):
            reason = f"Unsafe path escapes destination: {path}"
            raise ExportError(reason)
        try:
            schema, denormalized_metadata = self._to_dict(fmt)
            schema.dumpf(denormalized_metadata, path, **kwargs)
            logger.info(f"Exported {path}")
        except Exception:
            logger.exception(f"Could not export {fn}")

    def export_files(self, formats: frozenset[MetadataFormats] | None = None) -> None:
        """Export metadata to all supported file formats."""
        if self._config.general.dry_run:
            logger.info("Not exporting files.")
            return
        if not formats:
            formats = self._config.convert.export_formats
        if not formats:
            return

        for fmt in formats:
            self.to_file(fmt=fmt)

    def predict_filename(self) -> str:
        """
        Return the scheme filename this archive would be renamed to.

        The rendered name ends in ``ext``, which is a *metadata* field
        rather than the file's suffix. Left to the merge it can be missing
        (a config that skips or deletes it, whereupon comicfn2dict falls
        back to its "cbz" default) or stale (a value some tagger embedded
        in the archive), either of which names a PDF as a zip. The archive
        on disk is the authority, so its own suffix always wins.

        Returns "" when no usable name could be built, including a name
        that is nothing but an extension — renaming to that would make a
        hidden file.
        """
        schema, filename_md = self._to_dict(MetadataFormats.FILENAME)
        fn = schema.dumps(filename_md)
        if not fn or fn.startswith("."):
            return ""
        if self._path:
            fn = str(Path(fn).with_suffix(self._path.suffix))
        return fn

    @staticmethod
    def _is_same_file(old_path: Path, new_path: Path) -> bool:
        """Return whether both names already refer to one file on disk."""
        # Not just `==`: on a case-insensitive filesystem a rename that only
        # changes case lands on the same inode, and refusing it would make
        # `--rename` fail on every macOS library. `file_key`, not
        # `samefile`, because some filesystems give every file one inode.
        return file_key(new_path) == file_key(old_path)

    @staticmethod
    def _respell(old_path: Path, new_path: Path) -> bool:
        """
        Change the case of the name of a file the new name already finds.

        Return whether the old name is gone. Names that are a symbolic link
        and the file it names are left: renaming the link onto the file
        would replace the file with a link to itself. On a case-sensitive
        disk two hard links of one file can differ only in case, and
        rename() between them does nothing, so the old name is looked for
        afterwards, not assumed gone.
        """
        if not _differs_only_in_case(old_path, new_path):
            return False
        try:
            old_stat, new_stat = old_path.lstat(), new_path.lstat()
        except OSError:
            return False
        if (old_stat.st_dev, old_stat.st_ino) != (new_stat.st_dev, new_stat.st_ino):
            return False
        old_path.rename(new_path)
        return all(path.name != old_path.name for path in old_path.parent.iterdir())

    def _rename_to(self, old_path: Path, new_path: Path) -> bool:
        """
        Rename onto a destination no one else holds.

        Path.rename() replaces an existing destination silently on posix,
        so two archives whose metadata predicts one name -- the same issue
        carried twice, or a scheme that renders too few fields -- left only
        the last one written. Claim the destination for the same reason
        conversions do (comicbox.box.archive.write): the finished-file
        check alone can't see a rename still in flight on another thread.

        Return False when the new name already names this comic, through a
        hard or symbolic link, and nothing was renamed.
        """
        if self._is_same_file(old_path, new_path):
            return self._respell(old_path, new_path)
        _claim_destination(new_path, old_path)
        try:
            if new_path.exists():
                raise DestinationOccupiedError(old_path, new_path, "rename")
            old_path.rename(new_path)
        finally:
            _release_destination(new_path)
        return True

    def rename_file(self) -> None:
        """Rename the archive."""
        if not self._path:
            reason = "Cannot rename archive without a path."
            raise ArchiveWriteError(reason)
        fn = self.predict_filename()
        old_path = self._path
        if not fn:
            logger.warning(f"Unable to construct a filename for {old_path}")
            return
        new_path = self._path.parent / Path(fn)
        if new_path.name == old_path.name:
            # Already so named: nothing to do, and nothing to say.
            return
        if self._config.general.dry_run:
            logger.info(f"Would rename:\n{old_path} ==> {new_path}")
            return
        if not self._rename_to(old_path, new_path):
            logger.info(f"Not renamed: {new_path} is already a name for {old_path}")
            return
        self._path: Path | None = new_path
        logger.info(f"Renamed:\n{old_path} ==> {new_path}")

export_files(formats=None)

Export metadata to all supported file formats.

Source code in comicbox/box/dump_files.py
54
55
56
57
58
59
60
61
62
63
64
65
def export_files(self, formats: frozenset[MetadataFormats] | None = None) -> None:
    """Export metadata to all supported file formats."""
    if self._config.general.dry_run:
        logger.info("Not exporting files.")
        return
    if not formats:
        formats = self._config.convert.export_formats
    if not formats:
        return

    for fmt in formats:
        self.to_file(fmt=fmt)

predict_filename()

Return the scheme filename this archive would be renamed to.

The rendered name ends in ext, which is a metadata field rather than the file’s suffix. Left to the merge it can be missing (a config that skips or deletes it, whereupon comicfn2dict falls back to its “cbz” default) or stale (a value some tagger embedded in the archive), either of which names a PDF as a zip. The archive on disk is the authority, so its own suffix always wins.

Returns “” when no usable name could be built, including a name that is nothing but an extension — renaming to that would make a hidden file.

Source code in comicbox/box/dump_files.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def predict_filename(self) -> str:
    """
    Return the scheme filename this archive would be renamed to.

    The rendered name ends in ``ext``, which is a *metadata* field
    rather than the file's suffix. Left to the merge it can be missing
    (a config that skips or deletes it, whereupon comicfn2dict falls
    back to its "cbz" default) or stale (a value some tagger embedded
    in the archive), either of which names a PDF as a zip. The archive
    on disk is the authority, so its own suffix always wins.

    Returns "" when no usable name could be built, including a name
    that is nothing but an extension — renaming to that would make a
    hidden file.
    """
    schema, filename_md = self._to_dict(MetadataFormats.FILENAME)
    fn = schema.dumps(filename_md)
    if not fn or fn.startswith("."):
        return ""
    if self._path:
        fn = str(Path(fn).with_suffix(self._path.suffix))
    return fn

rename_file()

Rename the archive.

Source code in comicbox/box/dump_files.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def rename_file(self) -> None:
    """Rename the archive."""
    if not self._path:
        reason = "Cannot rename archive without a path."
        raise ArchiveWriteError(reason)
    fn = self.predict_filename()
    old_path = self._path
    if not fn:
        logger.warning(f"Unable to construct a filename for {old_path}")
        return
    new_path = self._path.parent / Path(fn)
    if new_path.name == old_path.name:
        # Already so named: nothing to do, and nothing to say.
        return
    if self._config.general.dry_run:
        logger.info(f"Would rename:\n{old_path} ==> {new_path}")
        return
    if not self._rename_to(old_path, new_path):
        logger.info(f"Not renamed: {new_path} is already a name for {old_path}")
        return
    self._path: Path | None = new_path
    logger.info(f"Renamed:\n{old_path} ==> {new_path}")

to_file(dest_path=None, fmt=MetadataFormats.COMICBOX_JSON, **kwargs)

Export metadatat to a file with a schema.

Source code in comicbox/box/dump_files.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def to_file(
    self,
    dest_path: Path | str | None = None,
    fmt: MetadataFormats = MetadataFormats.COMICBOX_JSON,
    **kwargs: Any,
) -> None:
    """Export metadatat to a file with a schema."""
    if dest_path is None:
        dest_path = self._config.general.dest_path
    dest_path = Path(dest_path)
    fn = fmt.value.filename
    path = dest_path / fn
    if not path.resolve().is_relative_to(dest_path.resolve()):
        reason = f"Unsafe path escapes destination: {path}"
        raise ExportError(reason)
    try:
        schema, denormalized_metadata = self._to_dict(fmt)
        schema.dumpf(denormalized_metadata, path, **kwargs)
        logger.info(f"Exported {path}")
    except Exception:
        logger.exception(f"Could not export {fn}")