Skip to content

comicbox.readinglists.cli.run ¶

What every comicbox readinglist action shares.

The run that holds an action’s arguments, consoles and failures; the checks that keep a write off an input or an existing file; and the worker that makes Ctrl-C a clean cancel.

Run ¶

One command: its arguments, its consoles and whether anything failed.

Source code in comicbox/readinglists/cli/run.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
class Run:
    """One command: its arguments, its consoles and whether anything failed."""

    def __init__(self, args: Namespace) -> None:
        """Hold the parsed arguments; open the consoles."""
        self.args = args
        self.out: Console = console()
        self.err: Console = console(stderr=True)
        self.failed = False
        # A usage error found after parsing, such as a -w format that
        # cannot hold the arc: exit 2, as argparse would.
        self.misused = False
        # Set by the user's Ctrl-C, so a spent quota is not taken for one.
        self.cancelled = False

    @property
    def log_level(self) -> str:
        """Get the logging level -Q asks for."""
        quiet = getattr(self.args, "quiet", 0)
        return _QUIET_LOGLEVELS.get(quiet, "CRITICAL") if quiet else "INFO"

    def fail(self, path: Path | None, error: BaseException) -> None:
        """Report one failure on stderr and carry on."""
        print_error(self.err, path, error)
        self.failed = True

    def misuse(self, message: str) -> None:
        """Report a usage error; the command exits 2."""
        print_error(self.err, None, ReadingListError(message))
        self.misused = True

    def load(self, path: Path) -> ReadingListResult | None:
        """Read a list and report what the read dropped, or why it failed."""
        try:
            result = load(path)
        except (OSError, ReadingListError) as exc:
            self.fail(path, exc)
            return None
        print_messages(self.err, result.warnings, f"{path}: warning")
        return result

    def refuse(self, problems: Sequence[tuple[Path, str]]) -> bool:
        """Report every destination problem; whether there were any."""
        for destination, reason in problems:
            self.fail(destination, ReadingListError(reason))
        return bool(problems)

    def write(
        self, reading_list: dict, fmt: ReadingListFormats, path: Path | None
    ) -> None:
        """Write a list to a file, or to stdout, after naming its losses."""
        print_messages(self.err, lost_fields(reading_list, fmt), "lost")
        text = dumps(reading_list, fmt)
        if path is None:
            self.out.out(text, end="" if text.endswith("\n") else "\n")
            return
        try:
            write_text(path, text.rstrip("\n") + "\n")
        except OSError as exc:
            self.fail(path, exc)
            return
        print_status(self.err, path, ok=True, detail=f"written as {fmt.value.label}")

    def no_keys(self, paths: Sequence[Path], lists: Sequence[Mapping]) -> None:
        """Say how many entries of each input can match nothing."""
        for path, reading_list in zip(paths, lists, strict=True):
            if count := _no_key_count(reading_list):
                what = (
                    "entry has no key and matches"
                    if count == 1
                    else "entries have no key and match"
                )
                message = f"{path}: {count} {what} nothing"
                print_messages(self.err, (message,), "warning")

    @property
    def exit_code(self) -> int:
        """2 for a usage error, 1 when any file failed."""
        return EXIT_USAGE if self.misused else int(self.failed)

exit_code property ¶

2 for a usage error, 1 when any file failed.

log_level property ¶

Get the logging level -Q asks for.

__init__(args) ¶

Hold the parsed arguments; open the consoles.

Source code in comicbox/readinglists/cli/run.py
136
137
138
139
140
141
142
143
144
145
146
def __init__(self, args: Namespace) -> None:
    """Hold the parsed arguments; open the consoles."""
    self.args = args
    self.out: Console = console()
    self.err: Console = console(stderr=True)
    self.failed = False
    # A usage error found after parsing, such as a -w format that
    # cannot hold the arc: exit 2, as argparse would.
    self.misused = False
    # Set by the user's Ctrl-C, so a spent quota is not taken for one.
    self.cancelled = False

fail(path, error) ¶

Report one failure on stderr and carry on.

Source code in comicbox/readinglists/cli/run.py
154
155
156
157
def fail(self, path: Path | None, error: BaseException) -> None:
    """Report one failure on stderr and carry on."""
    print_error(self.err, path, error)
    self.failed = True

load(path) ¶

Read a list and report what the read dropped, or why it failed.

Source code in comicbox/readinglists/cli/run.py
164
165
166
167
168
169
170
171
172
def load(self, path: Path) -> ReadingListResult | None:
    """Read a list and report what the read dropped, or why it failed."""
    try:
        result = load(path)
    except (OSError, ReadingListError) as exc:
        self.fail(path, exc)
        return None
    print_messages(self.err, result.warnings, f"{path}: warning")
    return result

misuse(message) ¶

Report a usage error; the command exits 2.

Source code in comicbox/readinglists/cli/run.py
159
160
161
162
def misuse(self, message: str) -> None:
    """Report a usage error; the command exits 2."""
    print_error(self.err, None, ReadingListError(message))
    self.misused = True

no_keys(paths, lists) ¶

Say how many entries of each input can match nothing.

Source code in comicbox/readinglists/cli/run.py
196
197
198
199
200
201
202
203
204
205
206
def no_keys(self, paths: Sequence[Path], lists: Sequence[Mapping]) -> None:
    """Say how many entries of each input can match nothing."""
    for path, reading_list in zip(paths, lists, strict=True):
        if count := _no_key_count(reading_list):
            what = (
                "entry has no key and matches"
                if count == 1
                else "entries have no key and match"
            )
            message = f"{path}: {count} {what} nothing"
            print_messages(self.err, (message,), "warning")

refuse(problems) ¶

Report every destination problem; whether there were any.

Source code in comicbox/readinglists/cli/run.py
174
175
176
177
178
def refuse(self, problems: Sequence[tuple[Path, str]]) -> bool:
    """Report every destination problem; whether there were any."""
    for destination, reason in problems:
        self.fail(destination, ReadingListError(reason))
    return bool(problems)

write(reading_list, fmt, path) ¶

Write a list to a file, or to stdout, after naming its losses.

Source code in comicbox/readinglists/cli/run.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def write(
    self, reading_list: dict, fmt: ReadingListFormats, path: Path | None
) -> None:
    """Write a list to a file, or to stdout, after naming its losses."""
    print_messages(self.err, lost_fields(reading_list, fmt), "lost")
    text = dumps(reading_list, fmt)
    if path is None:
        self.out.out(text, end="" if text.endswith("\n") else "\n")
        return
    try:
        write_text(path, text.rstrip("\n") + "\n")
    except OSError as exc:
        self.fail(path, exc)
        return
    print_status(self.err, path, ok=True, detail=f"written as {fmt.value.label}")

add_write_options(parser, output, help_text) ¶

Add --to, -o and --overwrite to an action.

Source code in comicbox/readinglists/cli/run.py
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
def add_write_options(parser: ArgumentParser, output: str, help_text: str) -> None:
    """Add ``--to``, ``-o`` and ``--overwrite`` to an action."""
    parser.add_argument(
        "--to",
        choices=FORMAT_TOKENS,
        default=DEFAULT_FORMAT.name.lower(),
        metavar="FMT",
        help=f"The format to write, yaml by default. One of: {', '.join(FORMAT_TOKENS)}.",
    )
    parser.add_argument("-o", "--output", type=Path, metavar=output, help=help_text)
    parser.add_argument(
        "--overwrite",
        action="store_true",
        help="Replace files that exist. An input is never written over.",
    )

cancellable(run, cancel, call, cancelling=FETCH_CANCELLING) ¶

Run call on a worker so the first Ctrl-C cancels it cleanly.

The first Ctrl-C calls cancel and says cancelling; the work stops at its next safe point, which for a fetch can wait out one rate-limit window. A second Ctrl-C quits at once.

Source code in comicbox/readinglists/cli/run.py
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
def cancellable(
    run: Run,
    cancel: Callable[[], None],
    call: Callable[[], _T],
    cancelling: str = FETCH_CANCELLING,
) -> _T:
    """
    Run ``call`` on a worker so the first Ctrl-C cancels it cleanly.

    The first Ctrl-C calls ``cancel`` and says ``cancelling``; the work
    stops at its next safe point, which for a fetch can wait out one
    rate-limit window. A second Ctrl-C quits at once.
    """
    outcome: list[Any] = []

    def work() -> None:
        try:
            outcome.append((True, call()))
        except BaseException as exc:
            outcome.append((False, exc))

    worker = threading.Thread(target=work, name="readinglist-work", daemon=True)
    try:
        # Started inside the try: a Ctrl-C the moment the work begins must
        # still cancel it, not leave it running.
        worker.start()
        while worker.is_alive():
            worker.join(_JOIN_POLL_SECONDS)
    except KeyboardInterrupt:
        run.cancelled = True
        cancel()
        print_note(run.err, cancelling)
        while worker.is_alive():
            worker.join(_JOIN_POLL_SECONDS)
    if not outcome:
        # Interrupted before the work could start: nothing was done.
        raise KeyboardInterrupt
    ok, value = outcome[0]
    if not ok:
        raise value
    return value

destination_problems(destinations, inputs, *, overwrite, make_parents=False) ¶

Name each destination that is an input, shared, taken or unreachable.

Source code in comicbox/readinglists/cli/run.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def destination_problems(
    destinations: Sequence[Path],
    inputs: Sequence[Path],
    *,
    overwrite: bool,
    make_parents: bool = False,
) -> list[tuple[Path, str]]:
    """Name each destination that is an input, shared, taken or unreachable."""
    checks = _Destinations(
        Counter(_same_file_key(path) for path in destinations),
        frozenset(_same_file_key(path) for path in inputs),
        overwrite,
        make_parents,
    )
    problems: list[tuple[Path, str]] = []
    reported: set[str] = set()
    for destination in destinations:
        key = _same_file_key(destination)
        if key not in reported and (reason := checks.problem(destination, key)):
            problems.append((destination, reason))
            reported.add(key)
    return problems

interrupts_ask(run, cancel) ¶

Make Ctrl-C only ask the writes to stop, however often it is pressed.

The first press calls cancel: no new write starts, and the writes under way finish. No press raises, so the process never exits with a write half done. Must be entered on the main thread.

Source code in comicbox/readinglists/cli/run.py
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
@contextmanager
def interrupts_ask(run: Run, cancel: Callable[[], None]) -> Generator[None]:
    """
    Make Ctrl-C only ask the writes to stop, however often it is pressed.

    The first press calls ``cancel``: no new write starts, and the writes
    under way finish. No press raises, so the process never exits with a
    write half done. Must be entered on the main thread.
    """

    def ask(_signum: int, _frame: object) -> None:
        if run.cancelled:
            print_note(run.err, WRITE_STILL_CANCELLING)
            return
        run.cancelled = True
        cancel()
        print_note(run.err, WRITE_CANCELLING)

    previous = signal.signal(signal.SIGINT, ask)
    try:
        yield
    finally:
        # Cancelled, the command now exits: still no press may interrupt it.
        signal.signal(signal.SIGINT, signal.SIG_IGN if run.cancelled else previous)

library_configs(*, delete_orig=False) ¶

Get the configs to read and to write a directory of comics with.

Both read every tag format a comic can carry, whatever read.formats says, so a tag file comicbox cannot parse is found wherever it is, and the formats written are built from all of the comic’s tags. The read config reads the file name as the user’s config says; the write config never does, so a write adds only the arc. Neither adds the config’s metadata, deletes its delete_keys or deletes all tags. delete_orig sets general.delete_orig for the writes, as the main CLI’s --delete-orig does.

Source code in comicbox/readinglists/cli/run.py
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
def library_configs(
    *, delete_orig: bool = False
) -> tuple["ComicboxSettings", "ComicboxSettings"]:
    """
    Get the configs to read and to write a directory of comics with.

    Both read every tag format a comic can carry, whatever ``read.formats``
    says, so a tag file comicbox cannot parse is found wherever it is, and
    the formats written are built from all of the comic's tags. The read
    config reads the file name as the user's config says; the write config
    never does, so a write adds only the arc. Neither adds the config's
    ``metadata``, deletes its ``delete_keys`` or deletes all tags.
    ``delete_orig`` sets ``general.delete_orig`` for the writes, as the
    main CLI's ``--delete-orig`` does.
    """
    from comicbox.config import get_config
    from comicbox.formats import MetadataFormats

    tag_keys = sorted(min(fmt.value.config_keys) for fmt in TAG_FORMATS)
    user = get_config(Namespace(comicbox=Namespace()))
    read_keys = list(tag_keys)
    if MetadataFormats.FILENAME in user.read.formats:
        read_keys.append(min(MetadataFormats.FILENAME.value.config_keys))
    return _library_config(read_keys), _library_config(
        tag_keys, delete_orig=delete_orig
    )

read_tagged_comics(run, directory, config=None) ¶

Read every comic under a directory, in path order.

A comic that cannot be read is one error line, and a directory one warning line; either way the command exits 1 and the rest are read.

Source code in comicbox/readinglists/cli/run.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
def read_tagged_comics(
    run: Run, directory: Path, config: "ComicboxSettings | None" = None
) -> Library:
    """
    Read every comic under a directory, in path order.

    A comic that cannot be read is one error line, and a directory one
    warning line; either way the command exits 1 and the rest are read.
    """
    if config is None:
        from comicbox.config import get_config

        config = get_config(Namespace(comicbox=Namespace()))
    previous = signal.signal(signal.SIGINT, _stop_reading(run))
    try:
        library = read_comics(directory, config, run.fail, log_level=run.log_level)
    finally:
        if not run.cancelled:
            signal.signal(signal.SIGINT, previous)
    for path, error in library.unread_directories.items():
        reason = error.strerror or str(error)
        print_messages(run.err, (f"{path}: {reason}; not searched",), "warning")
        run.failed = True
    return library

write_text(path, text) ¶

Write a UTF-8 file whole, or leave whatever was there.

Source code in comicbox/readinglists/cli/run.py
66
67
68
69
70
71
72
73
74
75
76
77
78
def write_text(path: Path, text: str) -> None:
    """Write a UTF-8 file whole, or leave whatever was there."""
    temp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
    try:
        temp.write_text(text, encoding="utf-8")
        temp.replace(path)
    except OSError as exc:
        if exc.filename is not None:
            # Name the destination, not the temporary file beside it.
            exc.filename = str(path)
        raise
    finally:
        temp.unlink(missing_ok=True)