Merge pull request #1098 from sirosen/non-standalone-exit
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Allow non-standalone ctx.exit() calls to return values rather than call sys.exit()
authored by David Lord · committed by GitHub · parents 011fd62, a94c0be · Browse files · 5 files·+81 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+81 added−2 removed
- tests:+47 added−0 removed
- other:+34 added−2 removed
Provenance
- Commit
8df9a6b- Tree
7594def- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
011fd62- Parent 2
a94c0be
5 files changed+81 added−2 removed
modified:click/core.py+22 added-2 removed
7 unmodified lines8 9 from .types import convert_type, IntRange, BOOL10 from .utils import make_str, make_default_short_help, echo, get_os_args11 from .exceptions import ClickException, UsageError, BadParameter, Abort, \12- MissingParameter12+ MissingParameter, Exit13 from .termui import prompt, confirm, style14 from .formatting import HelpFormatter, join_options15 from .parser import OptionParser, split_opt16 from .globals import push_context, pop_context480 unmodified lines497 raise Abort()498 499 def exit(self, code=0):500 """Exits the application with a given exit code."""501- sys.exit(code)501+ raise Exit(code)502 503 def get_usage(self):504 """Helper method to get formatted usage string for the current505 context and command.207 unmodified lines713 with self.make_context(prog_name, args, **extra) as ctx:714 rv = self.invoke(ctx)715 if not standalone_mode:716 return rv717+ # it's not safe to `ctx.exit(rv)` here!718+ # note that `rv` may actually contain data like "1" which719+ # has obvious effects720+ # more subtle case: `rv=[None, None]` can come out of721+ # chained commands which all returned `None` -- so it's not722+ # even always obvious that `rv` indicates success/failure723+ # by its truthiness/falsiness724 ctx.exit()725 except (EOFError, KeyboardInterrupt):726 echo(file=sys.stderr)727 raise Abort()6 unmodified lines734 if e.errno == errno.EPIPE:735 sys.exit(1)736 else:737 raise738+ except Exit as e:739+ if standalone_mode:740+ sys.exit(e.exit_code)741+ else:742+ # in non-standalone mode, return the exit code743+ # note that this is only reached if `self.invoke` above raises744+ # an Exit explicitly -- thus bypassing the check there which745+ # would return its result746+ # the results of non-standalone execution may therefore be747+ # somewhat ambiguous: if there are codepaths which lead to748+ # `ctx.exit(1)` and to `return 1`, the caller won't be able to749+ # tell the difference between the two750+ return e.exit_code751 except Abort:752 if not standalone_mode:753 raise754 echo('Aborted!', file=sys.stderr)1100 unmodified linesmodified:click/exceptions.py+10 added
221 unmodified lines222 223 224 class Abort(RuntimeError):225 """An internal signalling exception that signals Click to abort."""226+227+228+class Exit(RuntimeError):229+ """An exception that indicates that the application should exit with some230+ status code.231+232+ :param code: the status code to exit with.233+ """234+ def __init__(self, code=0):235+ self.exit_code = codemodified:tests/test_context.py+17 added
191 unmodified lines192 @click.command()193 @click.pass_context194 def cli(ctx):195 ctx.obj = 'test'196+197 @ctx.call_on_close198 def foo():199 assert click.get_current_context().obj == 'test'200 called.append(True)38 unmodified lines239 240 result = runner.invoke(cli, ['test2'])241 assert not result.exception242 assert result.output == 'foocmd\n'243+244+245+def test_exit_not_standalone():246+ @click.command()247+ @click.pass_context248+ def cli(ctx):249+ ctx.exit(1)250+251+ assert cli.main([], 'test_exit_not_standalone', standalone_mode=False) == 1252+253+ @click.command()254+ @click.pass_context255+ def cli(ctx):256+ ctx.exit(0)257+258+ assert cli.main([], 'test_exit_not_standalone', standalone_mode=False) == 0modified:tests/test_testing.py+30 added
152 unmodified lines153 click.echo('hello world')154 sys.exit('error')155 156 @click.command()157+ @click.pass_context158+ def cli_string_ctx_exit(ctx):159+ click.echo('hello world')160+ ctx.exit('error')161+162+ @click.command()163 def cli_int():164 click.echo('hello world')165 sys.exit(1)166 167 @click.command()168+ @click.pass_context169+ def cli_int_ctx_exit(ctx):170+ click.echo('hello world')171+ ctx.exit(1)172+173+ @click.command()174 def cli_float():175 click.echo('hello world')176 sys.exit(1.0)177 178 @click.command()179+ @click.pass_context180+ def cli_float_ctx_exit(ctx):181+ click.echo('hello world')182+ ctx.exit(1.0)183+184+ @click.command()185 def cli_no_error():186 click.echo('hello world')187 188 runner = CliRunner()1 unmodified line190 result = runner.invoke(cli_string)191 assert result.exit_code == 1192 assert result.output == 'hello world\nerror\n'193 194+ result = runner.invoke(cli_string_ctx_exit)195+ assert result.exit_code == 1196+ assert result.output == 'hello world\nerror\n'197+198 result = runner.invoke(cli_int)199 assert result.exit_code == 1200 assert result.output == 'hello world\n'201 202+ result = runner.invoke(cli_int_ctx_exit)203+ assert result.exit_code == 1204+ assert result.output == 'hello world\n'205+206 result = runner.invoke(cli_float)207 assert result.exit_code == 1208 assert result.output == 'hello world\n1.0\n'209 210+ result = runner.invoke(cli_float_ctx_exit)211+ assert result.exit_code == 1212+ assert result.output == 'hello world\n1.0\n'213+214 result = runner.invoke(cli_no_error)215 assert result.exit_code == 0216 assert result.output == 'hello world\n'217 72 unmodified linesmodified:CHANGES.rst+2 added
6 unmodified lines7 -----------8 9 (upcoming release with new features, release date to be decided)10 11+- 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