|
| 1 | +import sys |
| 2 | +import typing as t |
| 3 | +from dataclasses import dataclass |
| 4 | + |
| 5 | +import click |
| 6 | +from typer import Typer |
| 7 | +from typer.main import _typer_developer_exception_attr_name, except_hook, get_command |
| 8 | +from typer.models import DeveloperExceptionConfig |
| 9 | + |
| 10 | + |
| 11 | +@dataclass |
| 12 | +class _TyperClickCommand: |
| 13 | + command: click.Command |
| 14 | + name: t.Optional[str] |
| 15 | + |
| 16 | + |
| 17 | +class EllarCLITyper(Typer): |
| 18 | + """ |
| 19 | + Adapting Typer and Click Commands |
| 20 | + """ |
| 21 | + |
| 22 | + def __init__(self, *args: t.Any, **kwargs: t.Any) -> None: |
| 23 | + super().__init__(*args, **kwargs) |
| 24 | + self._click_commands: t.List[_TyperClickCommand] = [] |
| 25 | + |
| 26 | + def add_click_command( |
| 27 | + self, cmd: click.Command, name: t.Optional[str] = None |
| 28 | + ) -> None: |
| 29 | + self._click_commands.append(_TyperClickCommand(command=cmd, name=name)) |
| 30 | + |
| 31 | + def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any: |
| 32 | + if sys.excepthook != except_hook: |
| 33 | + sys.excepthook = except_hook # type: ignore[assignment] |
| 34 | + try: |
| 35 | + typer_click_commands = get_command(self) |
| 36 | + for item in self._click_commands: |
| 37 | + typer_click_commands.add_command(item.command, item.name) # type: ignore[attr-defined] |
| 38 | + return typer_click_commands(*args, **kwargs) |
| 39 | + except Exception as e: |
| 40 | + # Set a custom attribute to tell the hook to show nice exceptions for user |
| 41 | + # code. An alternative/first implementation was a custom exception with |
| 42 | + # raise custom_exc from e |
| 43 | + # but that means the last error shown is the custom exception, not the |
| 44 | + # actual error. This trick improves developer experience by showing the |
| 45 | + # actual error last. |
| 46 | + setattr( |
| 47 | + e, |
| 48 | + _typer_developer_exception_attr_name, |
| 49 | + DeveloperExceptionConfig( |
| 50 | + pretty_exceptions_enable=self.pretty_exceptions_enable, |
| 51 | + pretty_exceptions_show_locals=self.pretty_exceptions_show_locals, |
| 52 | + pretty_exceptions_short=self.pretty_exceptions_short, |
| 53 | + ), |
| 54 | + ) |
| 55 | + raise e |
0 commit comments