Skip to content

comicbox.box.print

Print Methods.

ComicboxPrint

Bases: ComicboxValidate

Print Methods.

Source code in comicbox/box/print.py
 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
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
class ComicboxPrint(ComicboxValidate):
    """Print Methods."""

    _CONSOLE = Console()

    def __init__(self, *args: Any, **kwargs: Any) -> None:
        """Set print variables."""
        super().__init__(*args, **kwargs)
        self._pygments_style_name = resolve_style_name(self._config.general.theme)
        self._style = ComicboxStyle(self._pygments_style_name)

    def _syntax(self, code: str, lexer: str) -> Syntax | str:
        """Apply rich syntax highlighting to code."""
        return (
            Syntax(
                code,
                lexer,
                theme=self._pygments_style_name,
                background_color="default",
                word_wrap=True,
            )
            if self._pygments_style_name
            else code
        )

    def _print(self, renderable: Pretty | Syntax | str) -> None:
        if self._pygments_style_name:
            self._CONSOLE.print(renderable)
        else:
            print(renderable)  # noqa: T201

    def print_section(
        self,
        title: Text | str,
        renderable: Pretty | Syntax | str,
        subtitle: str = "",
    ) -> None:
        """Pretty print a titled rule over a renderable."""
        if subtitle:
            title = (
                Text(str(title))
                + Text(": ")
                + Text(subtitle, style=self._style.subtitle)
            )

        self._CONSOLE.print(Rule(style=self._style.section_header))
        self._CONSOLE.print(title)
        self._print(renderable)

    def _print_version(self) -> None:
        """Print package version."""
        if PrintPhases.VERSION not in self._config.print.phases:
            return
        self._print(VERSION)

    def print_file_header(self) -> None:
        """Print header for this Archive's path."""
        if not self._path:
            return
        title = Text(str(self._path), style=self._style.path)
        self._CONSOLE.print(
            Rule(style=self._style.file_header, characters=_FILE_RULE_CHAR)
        )
        self._CONSOLE.print(title)

    def _print_file_type(self) -> None:
        """Print the file type."""
        if PrintPhases.FILE_TYPE not in self._config.print.phases:
            return
        ft = self.get_file_type()
        self._print(ft)

    def _print_file_names(self) -> None:
        """Print archive namelist."""
        if PrintPhases.FILE_NAMES not in self._config.print.phases:
            return
        namelist = self.namelist()
        pagenames = self.get_page_filenames()
        table = Table(style="cyan")
        table.add_column("Page")
        table.add_column("Archive Path")
        for name in namelist:
            try:
                index = str(pagenames.index(name))
            except Exception:
                index = ""
            index = index.rjust(3)
            table.add_row(index, name)
        self._CONSOLE.print(table)

    def _add_source_to_title(
        self,
        title: str,
        source: MetadataSources,
        source_data: Any,
        format_preposition: str = "as",
    ) -> Text:
        path = str(self._path) if source.value.from_archive else ""
        path = Text(path, style=self._style.path)
        if source_data.path or source == MetadataSources.ARCHIVE_COMMENT:
            in_archive_path = (
                "(comment)"
                if source == MetadataSources.ARCHIVE_COMMENT
                else source_data.path
            )
            path += Text(":") + Text(
                str(in_archive_path), style=self._style.in_archive_path
            )
        title_parts = [Text(title, style=self._style.section)]
        if path:
            title_parts.append(path)
        if source_data.fmt:
            title_parts.extend(
                [
                    Text(format_preposition, style=self._style.section),
                    Text(source_data.fmt.value.label, style=self._style.format),
                ]
            )
        result = Text("")
        first = True
        for part in title_parts:
            if not first:
                result += Text(" ")
            result += part
            first = False
        return result

    def _print_source(self, source: MetadataSources, source_data: Any) -> None:
        if not source_data or not source_data.data:
            return
        md = source_data.data
        if isinstance(md, Mapping):
            renderable = (
                Pretty(dict(md)) if self._pygments_style_name else str(dict(md))
            )
        else:
            print_md = md.decode(errors="replace") if isinstance(md, bytes) else md
            lexer = fmt.value.lexer if (fmt := source_data.fmt) else ""
            renderable = self._syntax(print_md, lexer)
        title = self._add_source_to_title(
            f"Source {source.value.label}", source, source_data
        )
        self.print_section(title, renderable)

    def _print_sources(self, source: MetadataSources) -> None:
        """Print source metadtata."""
        source_data_list = self.get_source_metadata(source)

        if not source_data_list:
            return
        for source_data in source_data_list:
            self._print_source(source, source_data)

    def _print_loaded(self, source: MetadataSources) -> None:
        """Print loaded metadata."""
        if PrintPhases.LOADED not in self._config.print.phases:
            return
        loaded_md_list = self.get_loaded_metadata(source)
        if not loaded_md_list:
            return
        for loaded_md in loaded_md_list:
            if not loaded_md:
                continue
            str_data = YamlRenderModule.dumps(dict(loaded_md.metadata))
            str_data = str_data.removesuffix("\n")
            syntax = self._syntax(str_data, "yaml")
            title = self._add_source_to_title(
                f"Loaded {source.value.label}", source, loaded_md
            )

            self.print_section(title, syntax)

    def _print_normalized(self, source: MetadataSources) -> None:
        """Print normalized metadata."""
        if PrintPhases.NORMALIZED not in self._config.print.phases:
            return
        normalized_md_list = self.get_normalized_metadata(source)
        if not normalized_md_list:
            return
        for normalized_md in normalized_md_list:
            if not normalized_md:
                continue
            schema = ComicboxYamlSchema(path=normalized_md.path)
            str_data = schema.dumps(dict(normalized_md.metadata))
            str_data = str_data.removesuffix("\n")
            syntax = self._syntax(str_data, "yaml")
            title = self._add_source_to_title(
                f"Normalized {source.value.label}",
                source,
                normalized_md,
                format_preposition="from",
            )

            self.print_section(title, syntax)

    def _print_sources_loaded_normalized(self) -> None:
        """Print sources, loaded, and normalized metadata."""
        if not _SOURCES_LOADED_NORMALIZED & self._config.print.phases:
            return
        for source in MetadataSources:
            if PrintPhases.SOURCE in self._config.print.phases:
                self._print_sources(source)
            if PrintPhases.LOADED in self._config.print.phases:
                self._print_loaded(source)
            if PrintPhases.NORMALIZED in self._config.print.phases:
                self._print_normalized(source)

    def _print_merged(self, schema: ComicboxYamlSchema) -> None:
        if PrintPhases.MERGED not in self._config.print.phases:
            return
        md = self.get_merged_metadata()
        str_data = schema.dumps(md)
        syntax = self._syntax(str_data, "yaml")
        title = Text("Merged for Compute")
        self.print_section(title, syntax)

    def _print_computed(self, schema: ComicboxYamlSchema) -> None:
        """Print computed metadata."""
        if PrintPhases.COMPUTED not in self._config.print.phases:
            return
        computed = self.get_computed_metadata()
        for computed_md in computed:
            if not computed_md or not computed_md.metadata:
                continue
            # For delete keys
            dump = bool(computed_md.merger)
            str_data = schema.dumps(
                computed_md.metadata,
                dump=dump,
            )
            syntax = self._syntax(str_data, "yaml")
            self.print_section(Text("Computed"), syntax, subtitle=computed_md.label)

    def _print_metadata(self) -> None:
        """Pretty print the metadata."""
        if (
            PrintPhases.METADATA in self._config.print.phases
            or PrintPhases.METADATA_OLD in self._config.print.phases
        ):
            md = self.to_string()
            syntax = self._syntax(md, "yaml")
            self.print_section("Merged Metadata", syntax)

    def print_out(self) -> None:
        """Print selections from config.print."""
        self._print_version()
        self._print_file_type()
        self._print_file_names()
        self._print_sources_loaded_normalized()
        schema = ComicboxYamlSchema(path=self._path)
        self._print_merged(schema)
        self._print_computed(schema)
        self._print_metadata()

__init__(*args, **kwargs)

Set print variables.

Source code in comicbox/box/print.py
 96
 97
 98
 99
100
def __init__(self, *args: Any, **kwargs: Any) -> None:
    """Set print variables."""
    super().__init__(*args, **kwargs)
    self._pygments_style_name = resolve_style_name(self._config.general.theme)
    self._style = ComicboxStyle(self._pygments_style_name)

print_file_header()

Print header for this Archive’s path.

Source code in comicbox/box/print.py
146
147
148
149
150
151
152
153
154
def print_file_header(self) -> None:
    """Print header for this Archive's path."""
    if not self._path:
        return
    title = Text(str(self._path), style=self._style.path)
    self._CONSOLE.print(
        Rule(style=self._style.file_header, characters=_FILE_RULE_CHAR)
    )
    self._CONSOLE.print(title)

print_out()

Print selections from config.print.

Source code in comicbox/box/print.py
334
335
336
337
338
339
340
341
342
343
def print_out(self) -> None:
    """Print selections from config.print."""
    self._print_version()
    self._print_file_type()
    self._print_file_names()
    self._print_sources_loaded_normalized()
    schema = ComicboxYamlSchema(path=self._path)
    self._print_merged(schema)
    self._print_computed(schema)
    self._print_metadata()

print_section(title, renderable, subtitle='')

Pretty print a titled rule over a renderable.

Source code in comicbox/box/print.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def print_section(
    self,
    title: Text | str,
    renderable: Pretty | Syntax | str,
    subtitle: str = "",
) -> None:
    """Pretty print a titled rule over a renderable."""
    if subtitle:
        title = (
            Text(str(title))
            + Text(": ")
            + Text(subtitle, style=self._style.subtitle)
        )

    self._CONSOLE.print(Rule(style=self._style.section_header))
    self._CONSOLE.print(title)
    self._print(renderable)

ComicboxStyle

Rich style definitions.

Source code in comicbox/box/print.py
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
class ComicboxStyle:
    """Rich style definitions."""

    def __init__(self, style_name: str) -> None:
        """Initialize styles by theme."""
        if not style_name:
            self.section_header = Style()
            self.file_header = Style()
            self.path = Style()
            self.in_archive_path = Style()
            self.format = Style()
            self.subtitle = Style()
            self.section = Style()
        else:
            theme = PygmentsSyntaxTheme(style_name)

            self.section_header = _make_style(theme, Name.Builtin)
            self.file_header = self.section_header
            if style_name == DEFAULT_STYLE_NAME:
                self.path = Style(color="cyan")
                self.in_archive_path = Style(color="cyan", bold=True)
            else:
                self.path = _make_style(theme, Generic.Output)
                self.in_archive_path = _make_style(theme, Generic.Heading)
            self.format = _make_style(theme, Name.Attribute)
            self.subtitle = _make_style(theme, String)
            self.section = _make_style(theme, Comment)

__init__(style_name)

Initialize styles by theme.

Source code in comicbox/box/print.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def __init__(self, style_name: str) -> None:
    """Initialize styles by theme."""
    if not style_name:
        self.section_header = Style()
        self.file_header = Style()
        self.path = Style()
        self.in_archive_path = Style()
        self.format = Style()
        self.subtitle = Style()
        self.section = Style()
    else:
        theme = PygmentsSyntaxTheme(style_name)

        self.section_header = _make_style(theme, Name.Builtin)
        self.file_header = self.section_header
        if style_name == DEFAULT_STYLE_NAME:
            self.path = Style(color="cyan")
            self.in_archive_path = Style(color="cyan", bold=True)
        else:
            self.path = _make_style(theme, Generic.Output)
            self.in_archive_path = _make_style(theme, Generic.Heading)
        self.format = _make_style(theme, Name.Attribute)
        self.subtitle = _make_style(theme, String)
        self.section = _make_style(theme, Comment)

resolve_style_name(theme)

Turn the general.theme setting into a pygments style name.

Unset means the default style, none means “” (plain text), and an unknown name warns and falls back to the default.

Source code in comicbox/box/print.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def resolve_style_name(theme: str | None) -> str:
    """
    Turn the ``general.theme`` setting into a pygments style name.

    Unset means the default style, ``none`` means "" (plain text), and an
    unknown name warns and falls back to the default.
    """
    if not theme:
        return DEFAULT_STYLE_NAME
    if theme.lower() == "none":
        return ""
    try:
        get_style_by_name(theme)
    except ClassNotFound as exc:
        logger.warning(exc)
        return DEFAULT_STYLE_NAME
    return theme