Skip to content

Commit 41dea8f

Browse files
authored
♻️ Create exceptions module and TyperException base class (#1942)
1 parent 407d924 commit 41dea8f

7 files changed

Lines changed: 49 additions & 52 deletions

File tree

‎typer/__init__.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,7 @@
55
from shutil import get_terminal_size as get_terminal_size
66

77
from . import colors as colors
8-
from ._click.exceptions import Abort as Abort
98
from ._click.exceptions import BadParameter as BadParameter
10-
from ._click.exceptions import Exit as Exit
119
from ._click.termui import confirm as confirm
1210
from ._click.termui import getchar as getchar
1311
from ._click.termui import progressbar as progressbar
@@ -19,6 +17,9 @@
1917
from ._click.utils import get_app_dir as get_app_dir
2018
from ._click.utils import get_binary_stream as get_binary_stream
2119
from ._click.utils import get_text_stream as get_text_stream
20+
from .exceptions import Abort as Abort
21+
from .exceptions import Exit as Exit
22+
from .exceptions import TyperException as TyperException
2223
from .main import Typer as Typer
2324
from .main import launch as launch
2425
from .main import run as run

‎typer/_click/core.py‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,9 @@
1616
overload,
1717
)
1818

19+
from ..exceptions import Abort, Exit
1920
from . import types
20-
from .exceptions import (
21-
Abort,
22-
BadParameter,
23-
Exit,
24-
MissingParameter,
25-
NoArgsIsHelpError,
26-
UsageError,
27-
)
21+
from .exceptions import BadParameter, MissingParameter, NoArgsIsHelpError, UsageError
2822
from .formatting import HelpFormatter
2923
from .globals import pop_context, push_context
3024
from .parser import _OptionParser

‎typer/_click/exceptions.py‎

Lines changed: 2 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from collections.abc import Sequence
22
from typing import IO, TYPE_CHECKING, Any, Union
33

4+
from ..exceptions import TyperException
45
from ._compat import get_text_stderr
56
from .globals import resolve_color_default
67
from .utils import echo, format_filename
@@ -16,23 +17,14 @@ def _join_param_hints(param_hint: Sequence[str] | str | None) -> str | None:
1617
return param_hint
1718

1819

19-
class ClickException(Exception):
20+
class ClickException(TyperException):
2021
"""An exception that Click can handle and show to the user."""
2122

22-
exit_code = 1
23-
2423
def __init__(self, message: str) -> None:
2524
super().__init__(message)
2625
# The context will be removed by the time we print the message, so cache
2726
# the color settings here to be used later on (in `show`)
2827
self.show_color: bool | None = resolve_color_default()
29-
self.message = message
30-
31-
def format_message(self) -> str:
32-
return self.message
33-
34-
def __str__(self) -> str:
35-
return self.message
3628

3729
def show(self, file: IO[Any] | None = None) -> None:
3830
if file is None:
@@ -243,18 +235,3 @@ def __init__(self, filename: str, hint: str | None = None) -> None:
243235

244236
def format_message(self) -> str:
245237
return f"Could not open file {self.ui_filename!r}: {self.message}"
246-
247-
248-
class Abort(RuntimeError):
249-
"""An internal signalling exception that signals Click to abort."""
250-
251-
252-
class Exit(RuntimeError):
253-
"""An exception that indicates that the application should exit with some
254-
status code.
255-
"""
256-
257-
__slots__ = ("exit_code",)
258-
259-
def __init__(self, code: int = 0) -> None:
260-
self.exit_code: int = code

‎typer/_click/termui.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
from contextlib import AbstractContextManager
44
from typing import IO, TYPE_CHECKING, Any, AnyStr, TextIO, TypeVar, overload
55

6-
from .exceptions import Abort, UsageError
6+
from ..exceptions import Abort
7+
from .exceptions import UsageError
78
from .globals import resolve_color_default
89
from .types import ParamType, convert_type
910
from .utils import LazyFile, echo

‎typer/_completion_shared.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
from . import _click
1010
from ._click.globals import get_current_context
11+
from .exceptions import Exit
1112

1213

1314
class Shells(str, Enum):
@@ -81,7 +82,7 @@ def get_completion_script(*, prog_name: str, complete_var: str, shell: str) -> s
8182
script = _completion_scripts.get(shell)
8283
if script is None:
8384
_click.echo(f"Shell {shell} not supported.", err=True)
84-
raise _click.exceptions.Exit(1)
85+
raise Exit(1)
8586
return (
8687
script
8788
% {
@@ -175,7 +176,7 @@ def install_powershell(*, prog_name: str, complete_var: str, shell: str) -> Path
175176
)
176177
if result.returncode != 0: # pragma: no cover
177178
_click.echo("Couldn't get PowerShell user profile", err=True)
178-
raise _click.exceptions.Exit(result.returncode)
179+
raise Exit(result.returncode)
179180
path_str = ""
180181
if isinstance(result.stdout, str): # pragma: no cover
181182
path_str = result.stdout
@@ -188,7 +189,7 @@ def install_powershell(*, prog_name: str, complete_var: str, shell: str) -> Path
188189
pass
189190
if not path_str: # pragma: no cover
190191
_click.echo("Couldn't decode the path automatically", err=True)
191-
raise _click.exceptions.Exit(1)
192+
raise Exit(1)
192193
path_obj = Path(path_str.strip())
193194
parent_dir: Path = path_obj.parent
194195
parent_dir.mkdir(parents=True, exist_ok=True)
@@ -234,7 +235,7 @@ def install(
234235
return shell, installed_path
235236
else:
236237
_click.echo(f"Shell {shell} is not supported.")
237-
raise _click.exceptions.Exit(1)
238+
raise Exit(1)
238239

239240

240241
def _get_shell_name() -> str | None:

‎typer/core.py‎

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
from ._click.parser import _OptionParser
1919
from ._click.shell_completion import CompletionItem
2020
from ._typing import Literal
21+
from .exceptions import Abort, Exit
2122
from .utils import parse_boolean_env_var
2223

2324
MarkupMode = Literal["markdown", "rich", None]
@@ -165,13 +166,10 @@ def _main(
165166
rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,
166167
**extra: Any,
167168
) -> Any:
168-
# Typer override, duplicated from _click.main() to handle custom rich exceptions
169-
# Verify that the environment is configured correctly, or reject
170-
# further execution to avoid a broken script.
169+
# Originally copied from _click.main(), adopted to handle custom rich exceptions etc
171170
if args is None:
172171
args = sys.argv[1:]
173172

174-
# Covered in Click tests
175173
if os.name == "nt" and windows_expand_args: # pragma: no cover
176174
args = _click.utils._expand_args(args)
177175
else:
@@ -199,20 +197,18 @@ def _main(
199197
ctx.exit()
200198
except EOFError as e:
201199
_click.echo(file=sys.stderr)
202-
raise _click.exceptions.Abort() from e
200+
raise Abort() from e
203201
except KeyboardInterrupt as e:
204-
raise _click.exceptions.Exit(130) from e
202+
raise Exit(130) from e
205203
except _click.exceptions.ClickException as e:
206204
if not standalone_mode:
207205
raise
208-
# Typer override
209206
if HAS_RICH and rich_markup_mode is not None:
210207
from . import rich_utils
211208

212209
rich_utils.rich_format_error(e)
213210
else:
214211
e.show()
215-
# Typer override end
216212
sys.exit(e.exit_code)
217213
except OSError as e:
218214
if e.errno == errno.EPIPE:
@@ -221,7 +217,7 @@ def _main(
221217
sys.exit(1)
222218
else:
223219
raise
224-
except _click.exceptions.Exit as e:
220+
except Exit as e:
225221
if standalone_mode:
226222
sys.exit(e.exit_code)
227223
else:
@@ -234,17 +230,15 @@ def _main(
234230
# `ctx.exit(1)` and to `return 1`, the caller won't be able to
235231
# tell the difference between the two
236232
return e.exit_code
237-
except _click.exceptions.Abort:
233+
except Abort:
238234
if not standalone_mode:
239235
raise
240-
# Typer override
241236
if HAS_RICH and rich_markup_mode is not None:
242237
from . import rich_utils
243238

244239
rich_utils.rich_abort_error()
245240
else:
246241
_click.echo(_("Aborted!"), file=sys.stderr)
247-
# Typer override end
248242
sys.exit(1)
249243

250244

‎typer/exceptions.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class TyperException(Exception):
2+
"""A Typer-specific exception"""
3+
4+
exit_code = 1
5+
6+
def __init__(self, message: str) -> None:
7+
super().__init__(message)
8+
self.message = message
9+
10+
def __str__(self) -> str:
11+
return self.message
12+
13+
def format_message(self) -> str:
14+
return self.message
15+
16+
17+
class Abort(RuntimeError):
18+
"""An internal signalling exception that signals Typer to abort."""
19+
20+
21+
class Exit(RuntimeError):
22+
"""An exception that indicates that the application should exit with some
23+
status code.
24+
"""
25+
26+
__slots__ = ("exit_code",)
27+
28+
def __init__(self, code: int = 0) -> None:
29+
self.exit_code: int = code

0 commit comments

Comments
 (0)