Skip to content
Myr

♻️ Create `exceptions` module and `TyperException` base class (#1942)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sofie Van Landeghem · committed by GitHub · parent 407d924 · Browse files · 7 files+49 added−52 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+49 added−52 removed

  • other:+49 added−52 removed

7 files+49 added−52 removed

modified:typer/_click/core.py+2 added-8 removed
14 unmodified lines
15 cast,16 overload,17)1819from ..exceptions import Abort, Exit20from . import types20from .exceptions import (21 Abort,22 BadParameter,23 Exit,24 MissingParameter,25 NoArgsIsHelpError,26 UsageError,27)21from .exceptions import BadParameter, MissingParameter, NoArgsIsHelpError, UsageError22from .formatting import HelpFormatter23from .globals import pop_context, push_context24from .parser import _OptionParser25from .termui import style
1084 unmodified lines
modified:typer/_click/exceptions.py+2 added-25 removed
1from collections.abc import Sequence2from typing import IO, TYPE_CHECKING, Any, Union34from ..exceptions import TyperException5from ._compat import get_text_stderr6from .globals import resolve_color_default7from .utils import echo, format_filename8
7 unmodified lines
1617 return param_hint181919class ClickException(Exception):20class ClickException(TyperException):21 """An exception that Click can handle and show to the user."""2222 exit_code = 12323 def __init__(self, message: str) -> None:24 super().__init__(message)25 # The context will be removed by the time we print the message, so cache26 # the color settings here to be used later on (in `show`)27 self.show_color: bool | None = resolve_color_default()29 self.message = message2831 def format_message(self) -> str:32 return self.message3334 def __str__(self) -> str:35 return self.message3629 def show(self, file: IO[Any] | None = None) -> None:30 if file is None:31 file = get_text_stderr()32
201 unmodified lines
234 self.filename = filename235236 def format_message(self) -> str:237 return f"Could not open file {self.ui_filename!r}: {self.message}"246247248class Abort(RuntimeError):249 """An internal signalling exception that signals Click to abort."""250251252class Exit(RuntimeError):253 """An exception that indicates that the application should exit with some254 status code.255 """256257 __slots__ = ("exit_code",)258259 def __init__(self, code: int = 0) -> None:260 self.exit_code: int = code
modified:typer/_click/termui.py+2 added-1 removed
1 unmodified line
2from collections.abc import Callable, Iterable3from contextlib import AbstractContextManager4from typing import IO, TYPE_CHECKING, Any, AnyStr, TextIO, TypeVar, overload56from ..exceptions import Abort6from .exceptions import Abort, UsageError7from .exceptions import UsageError8from .globals import resolve_color_default9from .types import ParamType, convert_type10from .utils import LazyFile, echo11
420 unmodified lines
modified:typer/__init__.py+3 added-2 removed
3 unmodified lines
45from shutil import get_terminal_size as get_terminal_size67from . import colors as colors8from ._click.exceptions import Abort as Abort8from ._click.exceptions import BadParameter as BadParameter10from ._click.exceptions import Exit as Exit9from ._click.termui import confirm as confirm10from ._click.termui import getchar as getchar11from ._click.termui import progressbar as progressbar12from ._click.termui import prompt as prompt
3 unmodified lines
16from ._click.utils import format_filename as format_filename17from ._click.utils import get_app_dir as get_app_dir18from ._click.utils import get_binary_stream as get_binary_stream19from ._click.utils import get_text_stream as get_text_stream20from .exceptions import Abort as Abort21from .exceptions import Exit as Exit22from .exceptions import TyperException as TyperException23from .main import Typer as Typer24from .main import launch as launch25from .main import run as run26from .models import CallbackParam as CallbackParam
7 unmodified lines
modified:typer/_completion_shared.py+5 added-4 removed
6 unmodified lines
7import shellingham89from . import _click10from ._click.globals import get_current_context11from .exceptions import Exit121314class Shells(str, Enum):15 bash = "bash"
65 unmodified lines
81 cf_name = _invalid_ident_char_re.sub("", prog_name.replace("-", "_"))82 script = _completion_scripts.get(shell)83 if script is None:84 _click.echo(f"Shell {shell} not supported.", err=True)84 raise _click.exceptions.Exit(1)85 raise Exit(1)86 return (87 script88 % {89 "complete_func": f"_{cf_name}_completion",
85 unmodified lines
175 stdout=subprocess.PIPE,176 )177 if result.returncode != 0: # pragma: no cover178 _click.echo("Couldn't get PowerShell user profile", err=True)178 raise _click.exceptions.Exit(result.returncode)179 raise Exit(result.returncode)180 path_str = ""181 if isinstance(result.stdout, str): # pragma: no cover182 path_str = result.stdout183 if isinstance(result.stdout, bytes):
4 unmodified lines
188 except UnicodeDecodeError: # pragma: no cover189 pass190 if not path_str: # pragma: no cover191 _click.echo("Couldn't decode the path automatically", err=True)191 raise _click.exceptions.Exit(1)192 raise Exit(1)193 path_obj = Path(path_str.strip())194 parent_dir: Path = path_obj.parent195 parent_dir.mkdir(parents=True, exist_ok=True)196 script_content = get_completion_script(
37 unmodified lines
234 )235 return shell, installed_path236 else:237 _click.echo(f"Shell {shell} is not supported.")237 raise _click.exceptions.Exit(1)238 raise Exit(1)239240241def _get_shell_name() -> str | None:242 """Get the current shell name, if available.
13 unmodified lines
modified:typer/core.py+6 added-12 removed
16 unmodified lines
17from ._click import types18from ._click.parser import _OptionParser19from ._click.shell_completion import CompletionItem20from ._typing import Literal21from .exceptions import Abort, Exit22from .utils import parse_boolean_env_var2324MarkupMode = Literal["markdown", "rich", None]25MARKUP_MODE_KEY = "TYPER_RICH_MARKUP_MODE"
139 unmodified lines
165 windows_expand_args: bool = True,166 rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,167 **extra: Any,168) -> Any:168 # Typer override, duplicated from _click.main() to handle custom rich exceptions169 # Verify that the environment is configured correctly, or reject170 # further execution to avoid a broken script.169 # Originally copied from _click.main(), adopted to handle custom rich exceptions etc170 if args is None:171 args = sys.argv[1:]172174 # Covered in Click tests173 if os.name == "nt" and windows_expand_args: # pragma: no cover174 args = _click.utils._expand_args(args)175 else:176 args = list(args)
19 unmodified lines
196 # by its truthiness/falsiness197 ctx.exit()198 except EOFError as e:199 _click.echo(file=sys.stderr)202 raise _click.exceptions.Abort() from e200 raise Abort() from e201 except KeyboardInterrupt as e:204 raise _click.exceptions.Exit(130) from e202 raise Exit(130) from e203 except _click.exceptions.ClickException as e:204 if not standalone_mode:205 raise208 # Typer override206 if HAS_RICH and rich_markup_mode is not None:207 from . import rich_utils208209 rich_utils.rich_format_error(e)210 else:211 e.show()215 # Typer override end212 sys.exit(e.exit_code)213 except OSError as e:214 if e.errno == errno.EPIPE:215 sys.stdout = cast(TextIO, _click.utils.PacifyFlushWrapper(sys.stdout))216 sys.stderr = cast(TextIO, _click.utils.PacifyFlushWrapper(sys.stderr))217 sys.exit(1)218 else:219 raise224 except _click.exceptions.Exit as e:220 except Exit as e:221 if standalone_mode:222 sys.exit(e.exit_code)223 else:224 # in non-standalone mode, return the exit code
4 unmodified lines
229 # somewhat ambiguous: if there are codepaths which lead to230 # `ctx.exit(1)` and to `return 1`, the caller won't be able to231 # tell the difference between the two232 return e.exit_code237 except _click.exceptions.Abort:233 except Abort:234 if not standalone_mode:235 raise240 # Typer override236 if HAS_RICH and rich_markup_mode is not None:237 from . import rich_utils238239 rich_utils.rich_abort_error()240 else:241 _click.echo(_("Aborted!"), file=sys.stderr)247 # Typer override end242 sys.exit(1)243244245class TyperArgument(_click.core.Parameter):
976 unmodified lines
added:typer/exceptions.py+29 added
1class TyperException(Exception):2 """A Typer-specific exception"""34 exit_code = 156 def __init__(self, message: str) -> None:7 super().__init__(message)8 self.message = message910 def __str__(self) -> str:11 return self.message1213 def format_message(self) -> str:14 return self.message151617class Abort(RuntimeError):18 """An internal signalling exception that signals Typer to abort."""192021class Exit(RuntimeError):22 """An exception that indicates that the application should exit with some23 status code.24 """2526 __slots__ = ("exit_code",)2728 def __init__(self, code: int = 0) -> None:29 self.exit_code: int = code