comicbox.cli

[docs] module comicbox.cli

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 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
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
"""Cli for comicbox."""

import sys
from argparse import Action, ArgumentParser, Namespace
from collections.abc import Sequence
from types import MappingProxyType
from typing import Any

from rich import box
from rich import print as rich_print
from rich.console import Group
from rich.style import Style
from rich.styled import Styled
from rich.table import Table
from rich.text import Text
from rich_argparse import RichHelpFormatter
from typing_extensions import override

from comicbox._pdf import PDF_ENABLED
from comicbox.exceptions import UnsupportedArchiveTypeError
from comicbox.formats import MetadataFormats
from comicbox.print import PrintPhases
from comicbox.run import Runner

_TABLE_ARGS = MappingProxyType(
    {
        "box": box.HEAVY,
        "border_style": "bright_black",
        "row_styles": ("", "on grey7"),
        "title_justify": "left",
    }
)
_HANDLED_EXCEPTIONS = (UnsupportedArchiveTypeError,)
_PRINT_PHASES_DESC = MappingProxyType(
    {
        "v": ("Software version", "v"),
        "t": ("File type", ""),
        "f": ("File names", "l"),
        "s": ("Source metadata", ""),
        "l": ("Loaded metadata sources", ""),
        "n": ("Loaded metadata normalized to comicbox schema", ""),
        "m": ("Merged normalized intermediate metadata", ""),
        "c": ("Computed metadata sources", ""),
        "p": ("Final metadata merged with computed sources", "p"),
    }
)
_METADATA_EXAMPLES = Styled(
    """
Metadata can be any tag from any of the supported metadata formats.
Complex [cyan]--metadata[/cyan] Examples:
  [cyan]-m[/cyan] 'Character: anna,bea,carol, contributors: {inker: [Other Name], writer: [Other Name, Writer Name]}, arcs: {Arc Name: 1, Other Arc Name: 5}'
  [cyan]-m[/cyan] '{publisher: My Press}'
  [cyan]-m[/cyan] \"Title: 'GI Robot: Foreign and Domestic'\"
  [cyan]-m[/cyan] \"series: 'Solarpunk: Kūchū Bōsōzoku'\"
""",
    style="argparse.text",
)
_DELETE_KEYS_EXAMPLES = Styled(
    """
Glom key paths are dot delimited. Numbers are list indexes. This deletes three comma delimited nested key paths:

  [cyan]-D[/cyan] [green]series,arcs.Across the Multiverse.number,reprints.0.series[/green]
    """,
    style="argparse.text",
)
_PDF_PAGE_FORMAT_DESC = MappingProxyType(
    {
        "pdf": "Extract pages as pdf file of one page.",
        "pixmap": "Extract pages as an uncompressed pixmap of the page.",
        "image": (
            "Extract the first image in it's original unaltered format on the page. "
            "Particularly useful when paired with [cyan]-z[/cyan] to convert comic PDFs to CBZs "
            "without reencoding the images."
        ),
    }
)
_QUIET_LOGLEVEL = MappingProxyType({1: "INFO", 2: "SUCCESS", 3: "WARNING", 4: "ERROR"})


class CSVAction(Action):
    """Parse comma delimited sequences."""

    @override
    def __call__(
        self,
        parser: ArgumentParser,
        namespace: Namespace,
        values: str | Sequence[Any] | None,
        option_string: str | None = None,
    ) -> None:
        """Parse comma delimited sequences."""
        if isinstance(values, str):
            values_array = values.split(",")
        elif isinstance(values, Sequence):
            values_array = values
        else:
            return
        setattr(namespace, self.dest, values_array)


class PageRangeAction(Action):
    """Parse page range."""

    @override
    def __call__(
        self,
        parser: ArgumentParser,
        namespace: Namespace,
        values: str | Sequence[Any] | None,
        option_string: str | None = None,
    ) -> None:
        """Parse page range delimited by :."""
        if isinstance(values, str):
            values = values.split(":")
        if not values:
            return

        index_from = int(values[0]) if len(values[0]) else None

        if len(values) == 1:
            index_to = index_from
        elif len(values[1]):
            index_to = int(values[1])
        else:
            index_to = None

        if index_from is not None:
            namespace.index_from = index_from
        if index_to is not None:
            namespace.index_to = index_to


def _get_help_print_phases_table() -> Table:
    table = Table(title="[dark_cyan]PRINT_PHASE[/dark_cyan] characters", **_TABLE_ARGS)  # pyright: ignore[reportArgumentType], # ty: ignore[invalid-argument-type]
    table.add_column("Phase", style="green")
    table.add_column("Description")
    table.add_column("Shortcut", style="cyan")
    for phase, attrs in _PRINT_PHASES_DESC.items():
        desc, shortcut = attrs
        if shortcut:
            shortcut = "-" + shortcut
        table.add_row(phase, desc, shortcut)
    return table


def _get_pdf_page_format_phases_table() -> Table:
    table = Table(title="[dark_cyan]PDF_PAGE_FORMAT[/dark_cyan] values", **_TABLE_ARGS)  # pyright: ignore[reportArgumentType], # ty: ignore[invalid-argument-type]
    table.add_column("Value", style="green")
    table.add_column("Description")
    for key, desc in _PDF_PAGE_FORMAT_DESC.items():
        table.add_row(key, desc)
    return table


FORMAT_TITLE = """Format keys for [cyan]--ignore-read[/cyan], [cyan]--write[/cyan], and [cyan]--export[/cyan]\n
Formats shown in order of precedence. [dim]Dimmed[/dim] formats are not indented for distribution and are provided as convenience to developers."""


def _get_help_format_table() -> Table:
    table = Table(title=FORMAT_TITLE, **_TABLE_ARGS)  # pyright: ignore[reportArgumentType], # ty: ignore[invalid-argument-type]
    table.add_column("Format")
    table.add_column("Keys", style="green")
    for fmt in reversed(MetadataFormats):
        if not fmt.value.enabled:
            continue
        label = fmt.value.label
        if label.startswith(("ComicTagger", "Comicbox")):
            style = Style(dim=True)
            label = Text(label, style=style)
        keys = ", ".join(sorted(fmt.value.config_keys))
        table.add_row(label, keys)

    return table


def _add_option_group(parser: ArgumentParser) -> None:
    option_group = parser.add_argument_group("Options")
    option_group.add_argument(
        "-c",
        "--config",
        metavar="CONFIG_PATH",
        action="store",
        help="Path to an alternate config file.",
    )
    option_group.add_argument(
        "-r",
        "--read",
        action=CSVAction,
        metavar="FORMATS",
        dest="read",
        help="Read metadata formats. Defaults to all.",
    )
    option_group.add_argument(
        "--read-ignore",
        action=CSVAction,
        metavar="FORMATS",
        dest="read_ignore",
        help="Subtract these formats from the read formats.",
    )
    option_group.add_argument(
        "-m",
        "--metadata",
        dest="metadata_cli",
        metavar="YAML_METADATA",
        action="append",
        help=(
            "Set metadata fields with linear YAML. (e.g.: [green]'keyA: value,"
            " keyB: [valueA,valueB,valueC], keyC: {subkey: {subsubkey: value}'[/green])"
            " Place a space after colons so they are properly parsed as YAML key"
            " value pairs. If your value contains a special YAML character (e.g."
            " :[]{}) quote the value. Linear YAML delineates subkeys with curly"
            " brackets in place of indentation."
        ),
    )
    option_group.add_argument(
        "-D",
        "--delete-keys",
        action=CSVAction,
        help=(
            "Delete a comma delimited list of comicbox glom key paths entirely from the final "
            "metadata. Example below."
        ),
    )
    option_group.add_argument(
        "-d",
        "--dest-path",
        help="destination path for extracting pages and metadata.",
    )
    option_group.add_argument(
        "--delete-orig",
        action="store_true",
        help="Delete the original cbr, cbt, or cb7 file if it was converted to a cbz successfully.",
    )
    option_group.add_argument(
        "--recurse",
        action="store_true",
        help="Perform selected actions recursively on a directory.",
    )
    option_group.add_argument(
        "-y",
        "--dry-run",
        action="store_true",
        help="Do not write anything to the filesystem. Report on what would be done.",
    )
    option_group.add_argument(
        "-g",
        "--compute-pages",
        dest="compute_pages",
        action="store_true",
        default=False,
        help=(
            "Compute the large ComicInfo style pages metadata from the archive. "
            "Turned off by default."
        ),
    )
    if PDF_ENABLED:
        option_group.add_argument(
            "-f",
            "--pdf-page-format",
            dest="pdf_page_format",
            action="store",
            default="",
            help="Method to extract pdf pages and covers. Valid values listed below.",
        )
    option_group.add_argument(
        "-A",
        "--no-compute-page-count",
        dest="compute_page_count",
        action="store_false",
        default=True,
        help=(
            "Do not compute the page count from the archive by reading the table of contents "
            "for image files."
        ),
    )
    option_group.add_argument(
        "-R",
        "--replace-metadata",
        action="store_true",
        default=False,
        help="Replace metadata keys instead of merging them.",
    )
    option_group.add_argument(
        "-Q",
        "--quiet",
        action="count",
        default=0,
        help=(
            "Increasingingly quiet success messages, warnings and errors with more Qs."
        ),
    )
    option_group.add_argument(
        "-s",
        "--stamp",
        dest="stamp",
        action="store_true",
        help=(
            "Normally comicbox will only update the notes (if enabled), tagger, and updated_at "
            "tags when performing a write or export action. This adds the stamps anyway."
        ),
    )
    option_group.add_argument(
        "-N",
        "--no-stamp-notes",
        dest="stamp_notes",
        action="store_false",
        help=(
            "Do not write the notes field with tagger, timestamp and identifiers "
            "when writing metadata out to a file."
        ),
    )
    option_group.add_argument(
        "-t",
        "--theme",
        help=(
            "Pygments theme to use for syntax highlighting. https://pygments.org/styles/. "
            "[green]'none'[/green] will stop highlighting."
        ),
    )


def _add_action_group(parser: ArgumentParser) -> None:
    action_group = parser.add_argument_group("Actions")
    action_group.add_argument(
        "-P",
        "--print-phases",
        dest="print",
        metavar="PRINT_PHASES",
        action="store",
        default="",
        help=(
            "Print separate phases of metadata processing."
            " Specify with a string that contains phase characters"
            " listed below. e.g. -P [green]slcm[/green]."
        ),
    )
    action_group.add_argument(
        "-v",
        "--version",
        action="store_true",
        help="Print software version. Shortcut for -P [green]v[/green]",
    )
    action_group.add_argument(
        "-V",
        "--validate",
        dest="validate",
        action="store_true",
        help=(
            "Validate formats against schema if available. Schemas like ComicInfo enforce a "
            "strict tag order. Schemas available at "
            "https://github.com/ajslater/comicbox/tree/main/schemas"
        ),
    )
    action_group.add_argument(
        "-p",
        "--print",
        dest="print_metadata",
        action="store_true",
        help="Print merged metadata. Shortcut for -P [green]p[/green].",
    )
    action_group.add_argument(
        "-l",
        "--list",
        dest="print_filenames",
        action="store_true",
        help="Print filenames in archive. Shortcut for -P [green]f[/green].",
    )
    action_group.add_argument(
        "-i",
        "--import",
        action="append",
        dest="import_paths",
        help="Import metadata from external files. Accepts quoted globs.",
    )
    action_group.add_argument(
        "-x",
        "--export",
        metavar="FORMATS",
        action=CSVAction,
        help="Export metadata as external files to --dest-path. Format keys listed below.",
    )
    action_group.add_argument(
        "--delete-all-tags",
        action="store_true",
        help="Delete all tags from the archive. Overrides --write.",
    )
    action_group.add_argument(
        "-e",
        "--pages",
        action=PageRangeAction,
        help=(
            "Extract a single page or : delimited range of pages by zero based index"
            " to --dest-path."
        ),
    )
    action_group.add_argument(
        "-o", "--covers", action="store_true", help="Extract cover pages."
    )
    action_group.add_argument(
        "-z",
        "--cbz",
        action="store_true",
        help=(
            "Export the archive to CBZ format and rewrite all metadata formats found. "
            "When converting PDFs, by default a pixmap is taken of the page. Try -a [green]image[/green] "
            "if the PDF is a comic with only one big image per page."
        ),
    )
    action_group.add_argument(
        "-w",
        "--write",
        metavar="FORMATS",
        action=CSVAction,
        help=(
            "Write comic metadata formats to archive cbt & cbr files are always"
            " exported to a cbz file. Format keys listed below."
        ),
    )
    action_group.add_argument(
        "--rename",
        action="store_true",
        help="Rename the file with comicbox's filename format.",
    )
    action_group.add_argument(
        "-h", "--help", action="help", help="Show only this help message and exit"
    )


def _add_target_group(parser: ArgumentParser) -> None:
    target_group = parser.add_argument_group("Targets")
    target_group.add_argument(
        "paths",
        nargs="*",
        help="Paths to comic archives or directories",
    )


def get_args(params: Sequence[str] | None = None) -> Namespace:
    """Get arguments and options."""
    description = "Comic book archive multi format metadata read/write/transform tool and image extractor."
    if not PDF_ENABLED:
        description += "\n[yellow]Comicbox is not installed with PDF support.[/yellow]"

    epilog = Group(
        _get_help_print_phases_table(),
        _METADATA_EXAMPLES,
        _DELETE_KEYS_EXAMPLES,
        _get_help_format_table(),
        _get_pdf_page_format_phases_table(),
    )

    parser = ArgumentParser(
        description=description,
        epilog=epilog,  # pyright: ignore[reportArgumentType] # ty: ignore[invalid-argument-type]
        formatter_class=RichHelpFormatter,
        add_help=False,
    )
    _add_option_group(parser)
    _add_action_group(parser)
    _add_target_group(parser)

    if params is not None:
        params = params[1:]
    return parser.parse_args(params)


def post_process_args(cns: Namespace) -> None:
    """Adjust CLI config."""
    # Print options
    if cns.version:
        cns.print += PrintPhases.VERSION.value
    if cns.print_filenames:
        cns.print += PrintPhases.FILE_NAMES.value
    if cns.print_metadata:
        cns.print += PrintPhases.METADATA.value

    # Loglevel
    if cns.quiet:
        cns.loglevel = _QUIET_LOGLEVEL.get(cns.quiet, "CRITICAL")


def main(params: Sequence[str] | None = None) -> None:
    """Get CLI arguments and perform the operation on the archive."""
    cns = get_args(params)
    post_process_args(cns)
    args = Namespace(comicbox=cns)

    runner = Runner(args)
    try:
        runner.run()
    except _HANDLED_EXCEPTIONS as exc:
        rich_print(f"[yellow]{exc}[/yellow]")
        sys.exit(1)