♻️ 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
Provenance
- Commit
41dea8f- Tree
74e12d5- Author
Sofie Van Landeghem <svlandeg@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
407d924
7 files changed+49 added−52 removed
modified:typer/_click/core.py+2 added-8 removed
14 unmodified lines15 cast,16 overload,17 )18 19+from ..exceptions import Abort, Exit20 from . import types20-from .exceptions import (21- Abort,22- BadParameter,23- Exit,24- MissingParameter,25- NoArgsIsHelpError,26- UsageError,27-)21+from .exceptions import BadParameter, MissingParameter, NoArgsIsHelpError, UsageError22 from .formatting import HelpFormatter23 from .globals import pop_context, push_context24 from .parser import _OptionParser25 from .termui import style1084 unmodified linesmodified:typer/_click/exceptions.py+2 added-25 removed
1 from collections.abc import Sequence2 from typing import IO, TYPE_CHECKING, Any, Union3 4+from ..exceptions import TyperException5 from ._compat import get_text_stderr6 from .globals import resolve_color_default7 from .utils import echo, format_filename8 7 unmodified lines16 17 return param_hint18 19 19-class ClickException(Exception):20+class ClickException(TyperException):21 """An exception that Click can handle and show to the user."""22 22- exit_code = 123-23 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 = message28 31- def format_message(self) -> str:32- return self.message33-34- def __str__(self) -> str:35- return self.message36-29 def show(self, file: IO[Any] | None = None) -> None:30 if file is None:31 file = get_text_stderr()32 201 unmodified lines234 self.filename = filename235 236 def format_message(self) -> str:237 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 some254- status code.255- """256-257- __slots__ = ("exit_code",)258-259- def __init__(self, code: int = 0) -> None:260- self.exit_code: int = codemodified:typer/_click/termui.py+2 added-1 removed
1 unmodified line2 from collections.abc import Callable, Iterable3 from contextlib import AbstractContextManager4 from typing import IO, TYPE_CHECKING, Any, AnyStr, TextIO, TypeVar, overload5 6+from ..exceptions import Abort6-from .exceptions import Abort, UsageError7+from .exceptions import UsageError8 from .globals import resolve_color_default9 from .types import ParamType, convert_type10 from .utils import LazyFile, echo11 420 unmodified linesmodified:typer/__init__.py+3 added-2 removed
3 unmodified lines4 5 from shutil import get_terminal_size as get_terminal_size6 7 from . import colors as colors8-from ._click.exceptions import Abort as Abort8 from ._click.exceptions import BadParameter as BadParameter10-from ._click.exceptions import Exit as Exit9 from ._click.termui import confirm as confirm10 from ._click.termui import getchar as getchar11 from ._click.termui import progressbar as progressbar12 from ._click.termui import prompt as prompt3 unmodified lines16 from ._click.utils import format_filename as format_filename17 from ._click.utils import get_app_dir as get_app_dir18 from ._click.utils import get_binary_stream as get_binary_stream19 from ._click.utils import get_text_stream as get_text_stream20+from .exceptions import Abort as Abort21+from .exceptions import Exit as Exit22+from .exceptions import TyperException as TyperException23 from .main import Typer as Typer24 from .main import launch as launch25 from .main import run as run26 from .models import CallbackParam as CallbackParam7 unmodified linesmodified:typer/_completion_shared.py+5 added-4 removed
6 unmodified lines7 import shellingham8 9 from . import _click10 from ._click.globals import get_current_context11+from .exceptions import Exit12 13 14 class Shells(str, Enum):15 bash = "bash"65 unmodified lines81 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 lines175 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 lines188 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 lines234 )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)239 240 241 def _get_shell_name() -> str | None:242 """Get the current shell name, if available.13 unmodified linesmodified:typer/core.py+6 added-12 removed
16 unmodified lines17 from ._click import types18 from ._click.parser import _OptionParser19 from ._click.shell_completion import CompletionItem20 from ._typing import Literal21+from .exceptions import Abort, Exit22 from .utils import parse_boolean_env_var23 24 MarkupMode = Literal["markdown", "rich", None]25 MARKUP_MODE_KEY = "TYPER_RICH_MARKUP_MODE"139 unmodified lines165 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:]172 174- # 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 lines196 # 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_utils208 209 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 code4 unmodified lines229 # 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_utils238 239 rich_utils.rich_abort_error()240 else:241 _click.echo(_("Aborted!"), file=sys.stderr)247- # Typer override end242 sys.exit(1)243 244 245 class TyperArgument(_click.core.Parameter):976 unmodified linesadded:typer/exceptions.py+29 added
1+class TyperException(Exception):2+ """A Typer-specific exception"""3+4+ exit_code = 15+6+ def __init__(self, message: str) -> None:7+ super().__init__(message)8+ self.message = message9+10+ def __str__(self) -> str:11+ return self.message12+13+ def format_message(self) -> str:14+ return self.message15+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 some23+ status code.24+ """25+26+ __slots__ = ("exit_code",)27+28+ def __init__(self, code: int = 0) -> None:29+ self.exit_code: int = code