Skip to content
Myr

Simplify Exit Exception

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

= Refactor BaseCommand to simplify Exit handling BaseCommand.main() will get the return value from `self.invoke` and pass it to `ctx.exit()`, so that commands which `return 1` will `ctx.exit(1)` This is not a behavioral change -- `ctx.exit()` already does this. Do not reraise Exit exceptions when invoked non-standalone. Instead, return their exit codes as the result of `BaseCommand.main`. So, a command which explicitly invokes `ctx.exit(0)` in its execution will effectively `return 0` instead of raising a specialized exception. = Make Exit its own RuntimeError subtype, don't pollute stdio on exit Exit exceptions should not be a subtype of ClickException with the output pretty-printing (`show()`) which happens when they are raised in non-standalone mode. That would make `ctx.exit(...)` needlessly pollute stderr. This would have downstream impact on everyone using context exit calls, and generally be a Bad Thing (tm). Instead, like Abort, Exit is a subclass of RuntimeError with very little "meat on its bones". It's an exception containing a single integer (exit code) which is then interpreted in that way in BaseCommand.main closes #533 closes #667

authored by Stephen Rosen · committed by Stephen Rosen · parent 225736b · Browse files · 4 files+32 added−53 removed
This commit

State

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

Diff stats

4 files+32 added−53 removed

  • tests:+4 added−13 removed
  • other:+28 added−40 removed

4 files+32 added−53 removed

modified:click/core.py+9 added-8 removed
496 unmodified lines
497 raise Abort()498499 def exit(self, code=0):500 """Exits the application with a given exit code."""501 raise Exit(code, self)501 raise Exit(code)502503 def get_usage(self):504 """Helper method to get formatted usage string for the current505 context and command.
207 unmodified lines
713 with self.make_context(prog_name, args, **extra) as ctx:714 rv = self.invoke(ctx)715 if not standalone_mode:716 return rv717 if not rv:718 rv = 0717 ctx.exit()719 ctx.exit(rv)720 except (EOFError, KeyboardInterrupt):721 echo(file=sys.stderr)722 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)723 except ClickException as e:724 if not standalone_mode:725 raise726 e.show()
2 unmodified lines
729 if e.errno == errno.EPIPE:730 sys.exit(1)731 else:732 raise733 except Exit as e:734 if standalone_mode:735 sys.exit(e.exit_code)736 else:737 return e.exit_code738 except Abort:739 if not standalone_mode:740 raise741 echo('Aborted!', file=sys.stderr)
1096 unmodified lines
modified:click/exceptions.py+17 added-32 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: '1617 def __init__(self, message):18 ctor_msg = message19 if PY2:
16 unmodified lines
3637 def show(self, file=None):38 if file is None:39 file = get_text_stderr()41 echo('%s%s' % (self.show_prefix, self.format_message()), file=file)40 echo('Error: %s' % self.format_message(), file=file)414244class ContextAwareException(ClickException):45 """An exception that knows how to use a :class:`~click.Context` object46 to properly display itself.43class UsageError(ClickException):44 """An internal exception that signals a usage error. This typically45 aborts any further handling.4647 :param message: the error message to display.48 :param ctx: optionally the context that caused this error. Click will49 fill in the context automatically in some situations.50 """51 exit_code = 25253 def __init__(self, message, ctx=None):54 ClickException.__init__(self, message)55 self.ctx = ctx56 self.cmd = self.ctx and self.ctx.command or None
9 unmodified lines
66 % (self.ctx.command_path, self.ctx.help_option_names[0]))67 if self.ctx is not None:68 color = self.ctx.color69 echo(self.ctx.get_usage() + '\n%s' % hint, file=file, color=color)69 echo('%s%s' % (self.show_prefix, self.format_message()), file=file, color=color)70 echo('Error: %s' % self.format_message(), file=file, color=color)717272class 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 = 2969773class BadParameter(UsageError):74 """An exception that formats out a standardized error message for a75 bad parameter. This is useful when thrown from a callback or type as76 Click will attach contextual information to it (for instance, which
145 unmodified lines
222223224class Abort(RuntimeError):225 """An internal signalling exception that signals Click to abort."""226227228class Exit(RuntimeError):229 """An exception that indicates that the application should exit with some230 status code.231232 :param code: the status code to exit with.233 """234 def __init__(self, code):235 self.exit_code = code
modified:tests/test_context.py+4 added-13 removed
1# -*- coding: utf-8 -*-2import pytest32import click345def test_ensure_context_objects(runner):
186 unmodified lines
192 @click.command()193 @click.pass_context194 def cli(ctx):195 ctx.obj = 'test'196197 @ctx.call_on_close198 def foo():199 assert click.get_current_context().obj == 'test'200 called.append(True)
40 unmodified lines
241 assert not result.exception242 assert result.output == 'foocmd\n'243244246def test_exit_not_standalone_failure():245def test_exit_not_standalone():246 @click.command()247 @click.pass_context248 def cli(ctx):249 ctx.exit(1)250252 with pytest.raises(click.exceptions.Exit) as e:253 cli.main([], 'test_exit_not_standalone', standalone_mode=False)254 assert e.value.exit_code == 1251 assert cli.main([], 'test_exit_not_standalone', standalone_mode=False) == 1252256257def test_exit_not_standalone_success():253 @click.command()254 @click.pass_context255 def cli(ctx):256 ctx.exit(0)257263 assert cli.main(264 [],265 'test_exit_not_standalone',266 standalone_mode=False,267 ) is None258 assert cli.main([], 'test_exit_not_standalone', standalone_mode=False) == 0
modified:CHANGES.rst+2 added
6 unmodified lines
7-----------89(upcoming release with new features, release date to be decided)1011- Non-standalone calls to Context.exit return the exit code, rather than12 calling ``sys.exit`` (`#667`_)(`#533`_)13- Updated test env matrix. (`#1027`_)14- Fixes a ZeroDivisionError in ProgressBar.make_step,15 when the arg passed to the first call of ProgressBar.update is 0. (`#1012`_)(`#447`_)16- Document that options can be required=True. (`#1022`_)(`#514`_)
542 unmodified lines