|
6 | 6 | # this notice are preserved.
|
7 | 7 | # === END LICENSE STATEMENT ===
|
8 | 8 | import logging
|
| 9 | +import sys |
9 | 10 | from pathlib import Path
|
10 | 11 | from typing import List, NoReturn, Optional
|
11 | 12 |
|
12 | 13 | import typer
|
| 14 | +from click.exceptions import ClickException |
| 15 | +from click.exceptions import UsageError as ClickUsageError |
13 | 16 | from rich.console import Console
|
14 | 17 | from rich.table import Table
|
| 18 | +from typer.rich_utils import rich_format_error |
15 | 19 | from typing_extensions import Annotated
|
16 | 20 |
|
17 | 21 | from labelle import __version__
|
@@ -554,9 +558,35 @@ def default(
|
554 | 558 | output_bitmap(bitmap, output)
|
555 | 559 |
|
556 | 560 |
|
| 561 | +def add_hint_about_text_option(e: ClickException) -> None: |
| 562 | + """Insert a suggestion to use the --text flag when a command is not found. |
| 563 | +
|
| 564 | + In dymoprint the --text option was implicit. If labelle is invoked without |
| 565 | + --text, it presents as a ClickUsageError with the message "No such command..." |
| 566 | + We append to this error message a hint to use the --text flag. |
| 567 | + """ |
| 568 | + if isinstance(e, ClickUsageError): |
| 569 | + # Enhance the error message for dymoprint users who are |
| 570 | + # not used to the --text flag being mandatory. |
| 571 | + if e.message.startswith("No such command '") and e.message.endswith("'."): |
| 572 | + command = e.message[17:-2] |
| 573 | + if " " in command: |
| 574 | + command = f'"{command}"' |
| 575 | + e.message += f""" Did you mean --text {command} ?""" |
| 576 | + |
| 577 | + |
557 | 578 | def main() -> None:
|
558 | 579 | configure_logging()
|
559 |
| - app() |
| 580 | + try: |
| 581 | + app(standalone_mode=False) |
| 582 | + except ClickException as e: |
| 583 | + # Use standalone mode to avoid typer's default error handling here: |
| 584 | + # <https://github.com/tiangolo/typer/blob/773927208fbf03d30d50fc39fe2a1a18b7bd93cb/typer/core.py#L207-L216> |
| 585 | + # This allows us to add the following hint: |
| 586 | + add_hint_about_text_option(e) |
| 587 | + |
| 588 | + rich_format_error(e) |
| 589 | + sys.exit(e.exit_code) |
560 | 590 |
|
561 | 591 |
|
562 | 592 | if __name__ == "__main__":
|
|
0 commit comments