Added support for BadParameter exceptions.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 2bab892 · Browse files · 8 files·+109 added−19 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+109 added−19 removed
- tests:+19 added−0 removed
- other:+90 added−19 removed
Provenance
- Commit
1407ecb- Tree
5110256- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
2bab892
8 files changed+109 added−19 removed
modified:click/__init__.py+4 added-2 removed
33 unmodified lines34 # Terminal functions35 from .termui import prompt, confirm, get_terminal_size, echo_via_pager36 37 # Exceptions38-from .exceptions import ClickException, UsageError, FileError, Abort38+from .exceptions import ClickException, UsageError, BadParameter, \39+ FileError, Abort40 41 # Formatting42 from .formatting import HelpFormatter, wrap_text43 21 unmodified lines65 # Terminal functions66 'prompt', 'confirm', 'get_terminal_size', 'echo_via_pager',67 68 # Exceptions68- 'ClickException', 'UsageError', 'FileError', 'Abort',69+ 'ClickException', 'UsageError', 'BadParameter', 'FileError',70+ 'Abort',71 72 # Formatting73 'HelpFormatter', 'wrap_text',74 3 unmodified linesmodified:click/core.py+29 added-6 removed
1 import os2 import sys3 import codecs4+from contextlib import contextmanager5 from itertools import chain, repeat6 7 from .types import convert_type, IntRange, BOOL8 from .utils import make_str, make_default_short_help, echo8-from .exceptions import ClickException, UsageError, Abort9+from .exceptions import ClickException, UsageError, BadParameter, Abort10 from .termui import prompt, confirm11 from .formatting import HelpFormatter12 from .parser import OptionParser, split_opt13 5 unmodified lines19 def batch(iterable, batch_size):20 return list(zip(*repeat(iter(iterable), batch_size)))21 22 23+@contextmanager24+def augment_usage_errors(ctx, param=None):25+ """Context manager that attaches extra information to exceptions that26+ fly.27+ """28+ try:29+ yield30+ except BadParameter as e:31+ if e.ctx is None:32+ e.ctx = ctx33+ if param is not None and e.param is None:34+ e.param = param35+ raise36+ except UsageError as e:37+ if e.ctx is None:38+ e.ctx = ctx39+ raise40+41+42 def iter_params_for_processing(invocation_order, declaration_order):43 """Given a sequence of parameters in the order as should be considered44 for processing and an iterable of parameters that exist, this returns45 a list in the correct order as they should be processed.206 unmodified lines252 253 args = args[2:]254 if getattr(callback, '__click_pass_context__', False):255 args = (self,) + args256+ with augment_usage_errors(self):236- return callback(*args, **kwargs)257+ return callback(*args, **kwargs)258 259 def forward(*args, **kwargs):260 """Similar to :meth:`forward` but fills in default keyword261 arguments from the current context if the other command expects608 unmodified lines870 rv = self.type.split_envvar_value(rv)871 return rv872 873 def handle_parse_result(self, ctx, opts, args):874+ with augment_usage_errors(ctx, param=self):853- value = self.consume_value(ctx, opts)854- value = self.full_process_value(ctx, value)855- if self.callback is not None:856- value = self.callback(ctx, value)875+ value = self.consume_value(ctx, opts)876+ value = self.full_process_value(ctx, value)877+ if self.callback is not None:878+ value = self.callback(ctx, value)879+880 if self.expose_value:881 ctx.params[self.name] = value882 return value, args883 301 unmodified linesmodified:click/exceptions.py+49 added-4 removed
13 unmodified lines14 else:15 Exception.__init__(self, message)16 self.message = message17 18+ def format_message(self):19+ return self.message20+21 def show(self, file=None):19- echo('Error: %s' % self.message)22+ echo('Error: %s' % self.format_message())23 24 25 class UsageError(ClickException):26 """An internal exception that signals a usage error. This typically27 aborts any further handling.28+29+ :param message: the error message to display.30+ :param ctx: optionally the context that caused this error. Click will31+ fill in the context automatically in some situations.32 """33 exit_code = 234 35 def __init__(self, message, ctx=None):2 unmodified lines38 39 def show(self, file=None):40 if self.ctx is not None:41 echo(self.ctx.get_usage() + '\n', file=file)35- echo('Error: %s' % self.message, file=file)42+ echo('Error: %s' % self.format_message(), file=file)43 44 45+class BadParameter(UsageError):46+ """An exception that formats out a standardized error message for a47+ bad parameter. This is useful when thrown from a callback or type as48+ click will attach contextual information to it (for instance like49+ which parameter it is).50+51+ .. versionadded:: 2.052+53+ :param param: the parameter object that caused this error. This can54+ be left and click if possible will attach this info55+ itself.56+ :param param_hint: a string that shows up as parameter name. This57+ can be used as alternative to `param` in cases58+ where custom validation should happen. If it is59+ a string it's used as such, if it's a list then60+ each item is quoted and separated.61+ """62+63+ def __init__(self, message, ctx=None, param=None,64+ param_hint=None):65+ UsageError.__init__(self, message, ctx)66+ self.param = param67+ self.param_hint = param_hint68+69+ def format_message(self):70+ if self.param_hint is not None:71+ param_hint = self.param_hint72+ elif self.param is not None:73+ param_hint = self.param.opts or [self.param.name]74+ else:75+ return 'Invalid value: %s' % self.message76+ if isinstance(param_hint, (tuple, list)):77+ param_hint = ' / '.join('"%s"' % x for x in param_hint)78+ return 'Invalid value for %s: %s' % (param_hint, self.message)79+80+81 class FileError(ClickException):82 """Raised if a file cannot be opened."""83 84 def __init__(self, filename, hint=None):85 ui_filename = filename_to_ui(filename)86 if hint is None:87 hint = 'unknown error'45- message = 'Could not open file %s: %s' % (filename, hint)46- ClickException.__init__(self, message)88+ ClickException.__init__(self, hint)89 self.ui_filename = ui_filename90 self.filename = filename91 92+ def format_message(self):93+ return 'Could not open file %s: %s' % (self.ui_filename, self.message)94 95+96 class Abort(RuntimeError):97 """An internal signalling exception that signals click to abort."""modified:click/types.py+2 added-7 removed
2 unmodified lines3 import stat4 import uuid5 6 from ._compat import open_stream, text_type, filename_to_ui, get_streerror7-from .exceptions import UsageError7+from .exceptions import BadParameter8 from .utils import safecall, LazyFile9 10 11 class ParamType(object):45 unmodified lines57 return (rv or '').split(self.envvar_list_splitter)58 59 def fail(self, message, param=None, ctx=None):60 """Helper method to fail with an invalid value message."""61- if param is None:62- message = 'Invalid value: %s' % message63- else:64- names = ' / '.join(param.opts) or param.name65- message = 'Invalid value for "%s": %s' % (names, message)66- raise UsageError(message, ctx=ctx)61+ raise BadParameter(message, ctx=ctx, param=param)62 63 64 class FuncParamType(ParamType):65 357 unmodified linesmodified:docs/api.rst+2 added
115 unmodified lines116 .. autoexception:: Abort117 118 .. autoexception:: UsageError119 120+.. autoexception:: BadParameter121+122 .. autoexception:: FileError123 124 Formatting125 ----------22 unmodified linesmodified:docs/changelog.rst+2 added
1+.. currentmodule:: click2+3 .. include:: ../CHANGESmodified:tests/test_options.py+19 added
106 unmodified lines107 result = runner.invoke(cmd, [], auto_envvar_prefix='TEST',108 env={'TEST_ARG': 'x 1 y 2'})109 assert not result.exception110 assert result.output == 'x|1\ny|2\n'111+112+113+def test_custom_validation(runner):114+ def validate_pos_int(ctx, value):115+ if value < 0:116+ raise click.BadParameter('Value needs to be positive')117+ return value118+119+ @click.command()120+ @click.option('--foo', callback=validate_pos_int, default=1)121+ def cmd(foo):122+ click.echo(foo)123+124+ result = runner.invoke(cmd, ['--foo', '-1'])125+ assert 'Invalid value for "--foo": Value needs to be positive' \126+ in result.output127+128+ result = runner.invoke(cmd, ['--foo', '42'])129+ assert result.output == '42\n'modified:CHANGES+2 added
10 unmodified lines11 - added support for opening stdin/stdout on windows in12 binary mode correctly.13 - added support for atomic writes to files by going through14 a temporary file.15+- introduced :exc:`BadParameter` which can be used to easily perform16+ custom validation with the same error messages as in the type system.17 18 Version 1.119 -----------20 11 unmodified lines