Skip to content
Myr

make context.exit raise a custom exception

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

This exception is caught in Command.main where we turn this into either an exception or a system exit. This allows context.exit to work when standalone_mode=False.

authored by Joe Jevnik · committed by Stephen Rosen · parent a0e0328 · Browse files · 3 files+65 added−10 removed
This commit

State

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

Diff stats

3 files+65 added−10 removed

  • tests:+25 added−1 removed
  • other:+40 added−9 removed

3 files+65 added−10 removed

modified:click/core.py+8 added-2 removed
7 unmodified lines
89from .types import convert_type, IntRange, BOOL10from .utils import make_str, make_default_short_help, echo, get_os_args11from .exceptions import ClickException, UsageError, BadParameter, Abort, \12 MissingParameter12 MissingParameter, Exit13from .termui import prompt, confirm, style14from .formatting import HelpFormatter, join_options15from .parser import OptionParser, split_opt16from .globals import push_context, pop_context
480 unmodified lines
497 raise Abort()498499 def exit(self, code=0):500 """Exits the application with a given exit code."""501 sys.exit(code)501 raise Exit(code, self)502503 def get_usage(self):504 """Helper method to get formatted usage string for the current505 context and command.
211 unmodified lines
717 ctx.exit()718 except (EOFError, KeyboardInterrupt):719 echo(file=sys.stderr)720 raise Abort()721 except Exit as e:722 if not standalone_mode:723 if e.exit_code:724 raise725 return None726 sys.exit(e.exit_code)727 except ClickException as e:728 if not standalone_mode:729 raise730 e.show()
1106 unmodified lines
modified:click/exceptions.py+32 added-7 removed
11 unmodified lines
12 """An exception that Click can handle and show to the user."""1314 #: The exit code for this exception15 exit_code = 116 show_prefix = 'Error: '1718 def __init__(self, message):19 ctor_msg = message20 if PY2:
16 unmodified lines
3738 def show(self, file=None):39 if file is None:40 file = get_text_stderr()40 echo('Error: %s' % self.format_message(), file=file)41 echo('%s%s' % (self.show_prefix, self.format_message()), file=file)424343class UsageError(ClickException):44 """An internal exception that signals a usage error. This typically45 aborts any further handling.44class ContextAwareException(ClickException):45 """An exception that knows how to use a :class:`~click.Context` object46 to properly display itself.4748 :param message: the error message to display.49 :param ctx: optionally the context that caused this error. Click will50 fill in the context automatically in some situations.51 """51 exit_code = 25252 def __init__(self, message, ctx=None):53 ClickException.__init__(self, message)54 self.ctx = ctx55 self.cmd = self.ctx and self.ctx.command or None
9 unmodified lines
65 % (self.ctx.command_path, self.ctx.help_option_names[0]))66 if self.ctx is not None:67 color = self.ctx.color68 echo(self.ctx.get_usage() + '\n%s' % hint, file=file, color=color)70 echo('Error: %s' % self.format_message(), file=file, color=color)69 echo('%s%s' % (self.show_prefix, self.format_message()), file=file, color=color)707172class Exit(ContextAwareException):73 """An exception that indicates that the application should exit with some74 status code.7576 :param code: the status code to exit with.77 :param ctx: optionally the context that caused this error. Click will78 fill in the context automatically in some situations.79 """80 show_prefix = 'Exit: '8182 def __init__(self, code, ctx=None):83 ContextAwareException.__init__(self, str(code), ctx=None)84 self.exit_code = code858687class UsageError(ContextAwareException):88 """An internal exception that signals a usage error. This typically89 aborts any further handling.9091 :param message: the error message to display.92 :param ctx: optionally the context that caused this error. Click will93 fill in the context automatically in some situations.94 """95 exit_code = 2969798class BadParameter(UsageError):99 """An exception that formats out a standardized error message for a100 bad parameter. This is useful when thrown from a callback or type as101 Click will attach contextual information to it (for instance, which
149 unmodified lines
modified:tests/test_context.py+25 added-1 removed
1# -*- coding: utf-8 -*-2import pytest34import click567def test_ensure_context_objects(runner):
197 unmodified lines
205 assert not result.exception206 assert result.output == 'aha!\n'207 assert called == [True]208207209def test_make_pass_decorator_args(runner):210 """211 Test to check that make_pass_decorator doesn't consume arguments based on212 invocation order.
26 unmodified lines
239240 result = runner.invoke(cli, ['test2'])241 assert not result.exception242 assert result.output == 'foocmd\n'243244def test_exit_not_standalone_failure():245 @click.command()246 @click.pass_context247 def cli(ctx):248 ctx.exit(1)249250 with pytest.raises(click.exceptions.Exit) as e:251 cli.main([], 'test_exit_not_standalone', standalone_mode=False)252 assert e.value.exit_code == 1253254255def test_exit_not_standalone_success():256 @click.command()257 @click.pass_context258 def cli(ctx):259 ctx.exit(0)260261 assert cli.main(262 [],263 'test_exit_not_standalone',264 standalone_mode=False,265 ) is None