Skip to content
Myr

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

8 files+109 added−19 removed

modified:click/__init__.py+4 added-2 removed
33 unmodified lines
34# Terminal functions35from .termui import prompt, confirm, get_terminal_size, echo_via_pager3637# Exceptions38from .exceptions import ClickException, UsageError, FileError, Abort38from .exceptions import ClickException, UsageError, BadParameter, \39 FileError, Abort4041# Formatting42from .formatting import HelpFormatter, wrap_text43
21 unmodified lines
65 # Terminal functions66 'prompt', 'confirm', 'get_terminal_size', 'echo_via_pager',6768 # Exceptions68 'ClickException', 'UsageError', 'FileError', 'Abort',69 'ClickException', 'UsageError', 'BadParameter', 'FileError',70 'Abort',7172 # Formatting73 'HelpFormatter', 'wrap_text',74
3 unmodified lines
modified:click/core.py+29 added-6 removed
1import os2import sys3import codecs4from contextlib import contextmanager5from itertools import chain, repeat67from .types import convert_type, IntRange, BOOL8from .utils import make_str, make_default_short_help, echo8from .exceptions import ClickException, UsageError, Abort9from .exceptions import ClickException, UsageError, BadParameter, Abort10from .termui import prompt, confirm11from .formatting import HelpFormatter12from .parser import OptionParser, split_opt13
5 unmodified lines
19def batch(iterable, batch_size):20 return list(zip(*repeat(iter(iterable), batch_size)))212223@contextmanager24def 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 raise404142def 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 lines
252253 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)258259 def forward(*args, **kwargs):260 """Similar to :meth:`forward` but fills in default keyword261 arguments from the current context if the other command expects
608 unmodified lines
870 rv = self.type.split_envvar_value(rv)871 return rv872873 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)879880 if self.expose_value:881 ctx.params[self.name] = value882 return value, args883
301 unmodified lines
modified:click/exceptions.py+49 added-4 removed
13 unmodified lines
14 else:15 Exception.__init__(self, message)16 self.message = message1718 def format_message(self):19 return self.message2021 def show(self, file=None):19 echo('Error: %s' % self.message)22 echo('Error: %s' % self.format_message())232425class UsageError(ClickException):26 """An internal exception that signals a usage error. This typically27 aborts any further handling.2829 :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 = 23435 def __init__(self, message, ctx=None):
2 unmodified lines
3839 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)434445class 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).5051 .. versionadded:: 2.05253 :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 """6263 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_hint6869 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)798081class FileError(ClickException):82 """Raised if a file cannot be opened."""8384 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 = filename9192 def format_message(self):93 return 'Could not open file %s: %s' % (self.ui_filename, self.message)949596class Abort(RuntimeError):97 """An internal signalling exception that signals click to abort."""
modified:click/types.py+2 added-7 removed
2 unmodified lines
3import stat4import uuid56from ._compat import open_stream, text_type, filename_to_ui, get_streerror7from .exceptions import UsageError7from .exceptions import BadParameter8from .utils import safecall, LazyFile91011class ParamType(object):
45 unmodified lines
57 return (rv or '').split(self.envvar_list_splitter)5859 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)626364class FuncParamType(ParamType):65
357 unmodified lines
modified:docs/api.rst+2 added
115 unmodified lines
116.. autoexception:: Abort117118.. autoexception:: UsageError119120.. autoexception:: BadParameter121122.. autoexception:: FileError123124Formatting125----------
22 unmodified lines
modified:docs/changelog.rst+2 added
1.. currentmodule:: click23.. include:: ../CHANGES
modified:tests/test_options.py+19 added
106 unmodified lines
107 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'111112113def 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 value118119 @click.command()120 @click.option('--foo', callback=validate_pos_int, default=1)121 def cmd(foo):122 click.echo(foo)123124 result = runner.invoke(cmd, ['--foo', '-1'])125 assert 'Invalid value for "--foo": Value needs to be positive' \126 in result.output127128 result = runner.invoke(cmd, ['--foo', '42'])129 assert result.output == '42\n'
modified:CHANGES+2 added
10 unmodified lines
11- 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.1718Version 1.119-----------20
11 unmodified lines