Skip to content
Myr

Bugfix for Exit handling

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

`rv = BaseCommand.invoke(ctx); ...; ctx.exit(rv)` seems correct at first blush, but there are actually important subtleties to consider here. For example, chained commands will produce a list of outputs, and that can have the consequence that `rv` is truthy -- but full of falsey values, possibly meant to indicate success. Stick with the existing simple `ctx.exit()` call (no args) so that we don't run into these behaviors. Add comments to `BaseCommand.main` explaining what's going on and why the logic is a little more nuanced than you might first guess.

authored by Stephen Rosen · committed by Stephen Rosen · parent 1602436 · Browse files · 2 files+17 added−4 removed
This commit

State

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

Diff stats

2 files+17 added−4 removed

  • other:+17 added−4 removed

2 files+17 added−4 removed

modified:click/core.py+16 added-3 removed
712 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 = 0719 ctx.exit(rv)717 # 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()728 except ClickException as e:
9 unmodified lines
738 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 raise
1097 unmodified lines
modified:click/exceptions.py+1 added-1 removed
229 unmodified lines
230 status code.231232 :param code: the status code to exit with.233 """234 def __init__(self, code):234 def __init__(self, code=0):235 self.exit_code = code