Skip to content
Myr

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

8 files+171 added−19 removed

modified:click/__init__.py+4 added-2 removed
22 unmodified lines
23 command, group, argument, option, confirmation_option, \24 password_option, version_option, help_option2526# Types27from .types import ParamType, File, Choice, STRING, INT, FLOAT, BOOL, UUID27from .types import ParamType, File, Choice, IntRange, STRING, INT, FLOAT, \28 BOOL, UUID2930# Helper functions31from .helpers import prompt, confirm, get_terminal_size, echo, echo_via_pager32
14 unmodified lines
47 'argument', 'option', 'confirmation_option', 'password_option',48 'version_option', 'help_option',4950 # Types50 'ParamType', 'File', 'Choice', 'STRING', 'INT', 'FLOAT', 'BOOL', 'UUID',51 'ParamType', 'File', 'Choice', 'IntRange', 'STRING', 'INT', 'FLOAT',52 'BOOL', 'UUID',5354 # Helper functions55 'prompt', 'confirm', 'get_terminal_size', 'echo', 'echo_via_pager',56
6 unmodified lines
modified:click/core.py+21 added-4 removed
1 unmodified line
2import sys3import codecs4from itertools import chain56from .types import convert_type, BOOL6from .types import convert_type, IntRange, BOOL7from .utils import make_str, make_default_short_help8from .exceptions import UsageError, Abort9from .helpers import prompt, confirm, echo10from .formatting import HelpFormatter
775 unmodified lines
786 :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 lines
798799 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 lines
831 self.is_flag = is_flag832 self.flag_value = flag_value833 self.multiple = multiple834835 self.count = count836 if count and type is None:837 self.type = IntRange(min=0)838839 if self.is_flag and isinstance(self.flag_value, bool) \840 and type is None:841 self.type = BOOL842 self.is_bool_flag = True
12 unmodified lines
855 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.')866867 def _parse_decls(self, decls):868 opts = []869 secondary_opts = []
29 unmodified lines
899 'dest': self.name,900 'nargs': self.nargs,901 }902891 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'909910 if self.is_flag:911 kwargs.pop('nargs', None)912 if self.is_bool_flag and self.secondary_opts:
127 unmodified lines
modified:click/parser.py+2 added
57 unmodified lines
58 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)6667
180 unmodified lines
modified:click/types.py+43 added
84 unmodified lines
8586class 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.8990 See :ref:`choice-opts` for an example.91 """92 name = 'choice'9394 def __init__(self, choices):
24 unmodified lines
119 def __repr__(self):120 return 'INT'121122123class 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.128129 See :ref:`ranges` for an example.130 """131 name = 'integer range'132133 def __init__(self, min=None, max=None, clamp=False):134 self.min = min135 self.max = max136 self.clamp = clamp137138 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 rv157158 def __repr__(self):159 return 'IntRange(%r, %r)' % (self.min, self.max)160161162class BoolParamType(ParamType):163 name = 'boolean'164165 def convert(self, value, param, ctx):
47 unmodified lines
213214 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.217218 See :ref:`file-args` for more information.219 """220 name = 'filename'221222 def __init__(self, mode='r', encoding=None, errors='strict'):
79 unmodified lines
modified:docs/options.rst+44 added-7 removed
76 unmodified lines
7778Counting79--------8081If you have used ``optparse`` or ``argparse`` before you might be missing82support for counting. This is a very rarely useful feature, usually only83useful for implementing verbosity flags. It can however be emulated by84using the multiple flag and taking the length of the end result:81In some very rare circumstances it's interesting to use the repeating of82options to count an integer up. This for instance can be used for83verbosity flags:8485.. click:example::8687 @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)9192And on the command line:9394.. click:run::
346 unmodified lines
441.. click:run::442443 invoke(chmod, args=['+w'])444 invoke(chmod, args=['-w'])445446.. _ranges:447448Range Options449-------------450451A special mention should go to the :class:`IntRange` type which works very452similar to the :data:`INT` type but restricts the value to fall into a453specific range (inclusive on both edges). It has two modes:454455- 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).461462Example:463464.. click:example::465466 @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)471472 if __name__ == '__main__':473 repeat()474475And from the command line:476477.. click:run::478479 invoke(repeat, args=['--count=1000', '--digit=5'])480 invoke(repeat, args=['--count=1000', '--digit=12'])481482If you pass ``None`` for any of the edges it means that the range is open483at that side.
modified:docs/parameters.rst+7 added-6 removed
53 unmodified lines
54:data:`click.UUID`:55 A parameter that accepts UUID values. This is not automatically56 guessed but represented as :class:`uuid.UUID`.5758: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:6062:class:`click.Choice`:63 A parameter that represents a choice of something. See64 :ref:`choice-opts` for an example.61.. autoclass:: Choice62 :noindex:6364.. autoclass:: IntRange65 :noindex:6667Custom parameter types can be implemented by subclassing68:class:`click.ParamType`. For simple cases passing a python function that69fails with a `ValueError` is also supported though discouraged.70
47 unmodified lines
modified:tests/test_basic.py+33 added
206 unmodified lines
207 result = runner.invoke(cli, ['--help'])208 assert '--method [foo|bar|baz]' in result.output209210211def 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)216217 result = runner.invoke(cli, ['--x=5'])218 assert not result.exception219 assert result.output == '5\n'220221 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.output225226 @click.command()227 @click.option('--x', type=click.IntRange(0, 5, clamp=True))228 def clamp(x):229 click.echo(x)230231 result = runner.invoke(clamp, ['--x=5'])232 assert not result.exception233 assert result.output == '5\n'234235 result = runner.invoke(clamp, ['--x=6'])236 assert not result.exception237 assert result.output == '5\n'238239 result = runner.invoke(clamp, ['--x=-1'])240 assert not result.exception241 assert result.output == '0\n'242243244def test_required_option(runner):245 @click.command()246 @click.option('--foo', required=True)247 def cli(foo):
5 unmodified lines
modified:tests/test_options.py+17 added
15 unmodified lines
1617 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 None202122def 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)2829 result = runner.invoke(cli, ['-vvv'])30 assert not result.exception31 assert result.output == 'verbosity=3\n'3233 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