Added count support and int ranges
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 fa467ce · Browse files · 8 files·+171 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+171 added−19 removed
- tests:+50 added−0 removed
- other:+121 added−19 removed
Provenance
- Commit
81930b5- Tree
7d44746- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
fa467ce
8 files changed+171 added−19 removed
modified:click/__init__.py+4 added-2 removed
22 unmodified lines23 command, group, argument, option, confirmation_option, \24 password_option, version_option, help_option25 26 # Types27-from .types import ParamType, File, Choice, STRING, INT, FLOAT, BOOL, UUID27+from .types import ParamType, File, Choice, IntRange, STRING, INT, FLOAT, \28+ BOOL, UUID29 30 # Helper functions31 from .helpers import prompt, confirm, get_terminal_size, echo, echo_via_pager32 14 unmodified lines47 'argument', 'option', 'confirmation_option', 'password_option',48 'version_option', 'help_option',49 50 # Types50- 'ParamType', 'File', 'Choice', 'STRING', 'INT', 'FLOAT', 'BOOL', 'UUID',51+ 'ParamType', 'File', 'Choice', 'IntRange', 'STRING', 'INT', 'FLOAT',52+ 'BOOL', 'UUID',53 54 # Helper functions55 'prompt', 'confirm', 'get_terminal_size', 'echo', 'echo_via_pager',56 6 unmodified linesmodified:click/core.py+21 added-4 removed
1 unmodified line2 import sys3 import codecs4 from itertools import chain5 6-from .types import convert_type, BOOL6+from .types import convert_type, IntRange, BOOL7 from .utils import make_str, make_default_short_help8 from .exceptions import UsageError, Abort9 from .helpers import prompt, confirm, echo10 from .formatting import HelpFormatter775 unmodified lines786 :param multiple: if this is set to True then the argument is accepted787 multiple times and recorded. This is similar to nargs788 in how it works but supports arbitrary number of789 arguments.790+ :param count: this flag makes an option increment an integer791 :param allow_from_autoenv: if this is enabled then the value of this792 parameter will be pulled from an environment793 variable in case a prefix is defined on the794 context.3 unmodified lines798 799 def __init__(self, param_decls=None, show_default=None,800 prompt=False, confirmation_prompt=False,801 hide_input=False, is_flag=None, flag_value=None,801- multiple=False, allow_from_autoenv=True, type=None,802- help=None, **attrs):802+ multiple=False, count=False, allow_from_autoenv=True,803+ type=None, help=None, **attrs):804 default_is_missing = attrs.get('default', _missing) is _missing805 Parameter.__init__(self, param_decls, type=type, **attrs)806 if prompt is True:807 prompt_text = self.name.replace('_', ' ').capitalize()23 unmodified lines831 self.is_flag = is_flag832 self.flag_value = flag_value833 self.multiple = multiple834 835+ self.count = count836+ if count and type is None:837+ self.type = IntRange(min=0)838+839 if self.is_flag and isinstance(self.flag_value, bool) \840 and type is None:841 self.type = BOOL842 self.is_bool_flag = True12 unmodified lines855 if self.is_bool_flag and self.hide_input \856 and self.prompt is not None:857 raise TypeError('Hidden input does not work with boolean '858 'flag prompts.')859+ if self.count:860+ if self.multiple:861+ raise TypeError('Options cannot be multiple and count '862+ 'at the same time.')863+ elif self.is_flag:864+ raise TypeError('Options cannot be count and flags at '865+ 'the same time.')866 867 def _parse_decls(self, decls):868 opts = []869 secondary_opts = []29 unmodified lines899 'dest': self.name,900 'nargs': self.nargs,901 }902 891- action = self.multiple and 'append' or 'store'903+ if self.multiple:904+ action = 'append'905+ elif self.count:906+ action = 'count'907+ else:908+ action = 'store'909 910 if self.is_flag:911 kwargs.pop('nargs', None)912 if self.is_bool_flag and self.secondary_opts:127 unmodified linesmodified:click/parser.py+2 added
57 unmodified lines58 elif self.action == 'append':59 opts.setdefault(self.dest, []).append(value)60 elif self.action == 'append_const':61 opts.setdefault(self.dest, []).append(self.const)62+ elif self.action == 'count':63+ opts[self.dest] = opts.get(self.dest, 0) + 164 else:65 raise ValueError('unknown action %r' % self.action)66 67 180 unmodified linesmodified:click/types.py+43 added
84 unmodified lines85 86 class Choice(ParamType):87 """The choice type allows a value to checked against a fixed set of88 supported values. All of these values have to be integers.89+90+ See :ref:`choice-opts` for an example.91 """92 name = 'choice'93 94 def __init__(self, choices):24 unmodified lines119 def __repr__(self):120 return 'INT'121 122 123+class IntRange(IntParamType):124+ """A parameter that works similar to :data:`click.INT` but restricts125+ the value to fit into a range. The default behavior is to fail if the126+ value falls outside the range, but it can also be silently clamped127+ between the two edges.128+129+ See :ref:`ranges` for an example.130+ """131+ name = 'integer range'132+133+ def __init__(self, min=None, max=None, clamp=False):134+ self.min = min135+ self.max = max136+ self.clamp = clamp137+138+ def convert(self, value, param, ctx):139+ rv = IntParamType.convert(self, value, param, ctx)140+ if self.clamp:141+ if self.min is not None and rv < self.min:142+ return self.min143+ if self.max is not None and rv > self.max:144+ return self.max145+ if self.min is not None and rv < self.min or \146+ self.max is not None and rv > self.max:147+ if self.min is None:148+ self.fail('%s is bigger than the maximum valid value '149+ '%s.' % (rv, self.max), param, ctx)150+ elif self.max is None:151+ self.fail('%s is smaller than the minimum valid value '152+ '%s.' % (rv, self.min), param, ctx)153+ else:154+ self.fail('%s is not in the valid range of %s to %s.'155+ % (rv, self.min, self.max), param, ctx)156+ return rv157+158+ def __repr__(self):159+ return 'IntRange(%r, %r)' % (self.min, self.max)160+161+162 class BoolParamType(ParamType):163 name = 'boolean'164 165 def convert(self, value, param, ctx):47 unmodified lines213 214 By default the file is opened for reading text data but it can also be215 opened in binary mode or for writing. The encoding parameter can be used216 to force a specific encoding.217+218+ See :ref:`file-args` for more information.219 """220 name = 'filename'221 222 def __init__(self, mode='r', encoding=None, errors='strict'):79 unmodified linesmodified:docs/options.rst+44 added-7 removed
76 unmodified lines77 78 Counting79 --------80 81-If you have used ``optparse`` or ``argparse`` before you might be missing82-support for counting. This is a very rarely useful feature, usually only83-useful for implementing verbosity flags. It can however be emulated by84-using the multiple flag and taking the length of the end result:81+In some very rare circumstances it's interesting to use the repeating of82+options to count an integer up. This for instance can be used for83+verbosity flags:84 85 .. click:example::86 87 @click.command()89- @click.option('-v', '--verbose', is_flag=True, multiple=True)88+ @click.option('-v', '--verbose', count=True)89 def log(verbose):91- verbosity = len(verbose)92- click.echo('Verbosity: %s' % verbosity)90+ click.echo('Verbosity: %s' % verbose)91 92 And on the command line:93 94 .. click:run::346 unmodified lines441 .. click:run::442 443 invoke(chmod, args=['+w'])444 invoke(chmod, args=['-w'])445+446+.. _ranges:447+448+Range Options449+-------------450+451+A special mention should go to the :class:`IntRange` type which works very452+similar to the :data:`INT` type but restricts the value to fall into a453+specific range (inclusive on both edges). It has two modes:454+455+- the default mode (non clamping mode) where a value that falls outside456+ of the range will cause an error.457+- an optional clamping mode where a value that falls outside of the458+ range will be clamped. This means that a range of ``0-5`` would459+ return ``5`` for the value ``10`` or ``0`` for the value ``-1`` (for460+ example).461+462+Example:463+464+.. click:example::465+466+ @click.command()467+ @click.option('--count', type=click.IntRange(0, 20, clamp=True))468+ @click.option('--digit', type=click.IntRange(0, 10))469+ def repeat(count, digit):470+ click.echo(str(digit) * count)471+472+ if __name__ == '__main__':473+ repeat()474+475+And from the command line:476+477+.. click:run::478+479+ invoke(repeat, args=['--count=1000', '--digit=5'])480+ invoke(repeat, args=['--count=1000', '--digit=12'])481+482+If you pass ``None`` for any of the edges it means that the range is open483+at that side.modified:docs/parameters.rst+7 added-6 removed
53 unmodified lines54 :data:`click.UUID`:55 A parameter that accepts UUID values. This is not automatically56 guessed but represented as :class:`uuid.UUID`.57 58-:class:`click.File`:59- A parameter that is an opened file. It can be opened for reading or60- writing. See :ref:`file-args` for an example.58+.. autoclass:: File59+ :noindex:60 62-:class:`click.Choice`:63- A parameter that represents a choice of something. See64- :ref:`choice-opts` for an example.61+.. autoclass:: Choice62+ :noindex:63 64+.. autoclass:: IntRange65+ :noindex:66+67 Custom parameter types can be implemented by subclassing68 :class:`click.ParamType`. For simple cases passing a python function that69 fails with a `ValueError` is also supported though discouraged.70 47 unmodified linesmodified:tests/test_basic.py+33 added
206 unmodified lines207 result = runner.invoke(cli, ['--help'])208 assert '--method [foo|bar|baz]' in result.output209 210 211+def test_int_range_option(runner):212+ @click.command()213+ @click.option('--x', type=click.IntRange(0, 5))214+ def cli(x):215+ click.echo(x)216+217+ result = runner.invoke(cli, ['--x=5'])218+ assert not result.exception219+ assert result.output == '5\n'220+221+ result = runner.invoke(cli, ['--x=6'])222+ assert result.exit_code == 2223+ assert 'Invalid value for "--x": 6 is not in the valid range of 0 to 5.\n' \224+ in result.output225+226+ @click.command()227+ @click.option('--x', type=click.IntRange(0, 5, clamp=True))228+ def clamp(x):229+ click.echo(x)230+231+ result = runner.invoke(clamp, ['--x=5'])232+ assert not result.exception233+ assert result.output == '5\n'234+235+ result = runner.invoke(clamp, ['--x=6'])236+ assert not result.exception237+ assert result.output == '5\n'238+239+ result = runner.invoke(clamp, ['--x=-1'])240+ assert not result.exception241+ assert result.output == '0\n'242+243+244 def test_required_option(runner):245 @click.command()246 @click.option('--foo', required=True)247 def cli(foo):5 unmodified linesmodified:tests/test_options.py+17 added
15 unmodified lines16 17 result = runner.invoke(cli, ['--help'])18 assert re.search(r'\+\+foo\s+das foo', result.output) is not None19 assert re.search(r'--bar\s+das bar', result.output) is not None20+21+22+def test_counting(runner):23+ @click.command()24+ @click.option('-v', count=True, help='Verbosity',25+ type=click.IntRange(0, 3))26+ def cli(v):27+ click.echo('verbosity=%d' % v)28+29+ result = runner.invoke(cli, ['-vvv'])30+ assert not result.exception31+ assert result.output == 'verbosity=3\n'32+33+ result = runner.invoke(cli, ['-vvvv'])34+ assert result.exception35+ assert 'Invalid value for "-v": 4 is not in the valid range of 0 to 3.' \36+ in result.output