Better handling of help text for dynamic default option values
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Doug Harris · committed by Doug Harris · parent 43cb986 · Browse files · 4 files·+80 added−11 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+80 added−11 removed
- tests:+27 added−1 removed
- other:+53 added−10 removed
Provenance
- Commit
1ac1fb3- Tree
24d8bb3- Author
Doug Harris <dharris@truthinitiative.org>- Committer
Doug Harris <dharris@truthinitiative.org>- Parent
43cb986
4 files changed+80 added−11 removed
modified:click/core.py+15 added-6 removed
1 import errno2+import inspect3 import os4 import sys5 from contextlib import contextmanager6 from itertools import repeat7 unmodified lines14 from .formatting import HelpFormatter, join_options15 from .parser import OptionParser, split_opt16 from .globals import push_context, pop_context17 17-from ._compat import PY2, isidentifier, iteritems18+from ._compat import PY2, isidentifier, iteritems, string_types19 from ._unicodefun import _check_for_unicode_literals, _verify_python3_env20 21 22 _missing = object()1421 unmodified lines1444 1445 All other parameters are passed onwards to the parameter constructor.1446 1447 :param show_default: controls if the default value should be shown on the1447- help page. Normally, defaults are not shown.1448+ help page. Normally, defaults are not shown. If this1449+ value is a string, it shows the string instead of the1450+ value. This is particularly useful for dynamic options.1451 :param show_envvar: controls if an environment variable should be shown on1452 the help page. Normally, environment variables1453 are not shown.1454 :param prompt: if set to `True` or a non empty string then the user will be200 unmodified lines1655 ', '.join('%s' % d for d in envvar)1656 if isinstance(envvar, (list, tuple))1657 else envvar, ))1658 if self.default is not None and self.show_default:1656- extra.append('default: %s' % (1657- ', '.join('%s' % d for d in self.default)1658- if isinstance(self.default, (list, tuple))1659- else self.default, ))1659+ if isinstance(self.show_default, string_types):1660+ default_string = '({})'.format(self.show_default)1661+ elif isinstance(self.default, (list, tuple)):1662+ default_string = ', '.join('%s' % d for d in self.default)1663+ elif inspect.isfunction(self.default):1664+ default_string = "(dynamic)"1665+ else:1666+ default_string = self.default1667+ extra.append('default: {}'.format(default_string))1668+1669 if self.required:1670 extra.append('required')1671 if extra:1672 help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra))125 unmodified linesmodified:docs/options.rst+28 added
43 unmodified lines44 45 In this case the option is of type :data:`INT` because the default value46 is an integer.47 48+To show the default values when showing command help, use ``show_default=True``49+50+.. click:example::51+52+ @click.command()53+ @click.option('--n', default=1, show_default=True)54+ def dots(n):55+ click.echo('.' * n)56+57+.. click:run::58+59+ invoke(dots, args=['--help'])60+61 Multi Value Options62 -------------------63 64 Sometimes, you have options that take more than one argument. For options,336 unmodified lines401 default=lambda: os.environ.get('USER', ''))402 def hello(username):403 print("Hello,", username)404 405+To describe what the default value will be, set it in ``show_default``.406+407+.. click:example::408+409+ @click.command()410+ @click.option('--username', prompt=True,411+ default=lambda: os.environ.get('USER', ''),412+ show_default='current user')413+ def hello(username):414+ print("Hello,", username)415+416+.. click:run::417+418+ invoke(hello, args=['--help'])419+420 Callbacks and Eager Options421 ---------------------------422 423 Sometimes, you want a parameter to completely change the execution flow.315 unmodified linesmodified:tests/test_options.py+27 added-1 removed
172 unmodified lines173 result = runner.invoke(cmd, '--arg1 a b --arg1 test 1 --arg2 2 '174 'two --arg2 4 four'.split())175 assert not result.exception176 177+def test_dynamic_default_help_unset(runner):178+ @click.command()179+ @click.option('--username', prompt=True,180+ default=lambda: os.environ.get('USER', ''),181+ show_default=True)182+ def cmd(username):183+ print("Hello,", username)184 185+ result = runner.invoke(cmd, ['--help'])186+ assert result.exit_code == 0187+ assert '--username' in result.output188+ assert 'lambda' not in result.output189+ assert '(dynamic)' in result.output190+191+def test_dynamic_default_help_text(runner):192+ @click.command()193+ @click.option('--username', prompt=True,194+ default=lambda: os.environ.get('USER', ''),195+ show_default='current user')196+ def cmd(username):197+ print("Hello,", username)198+199+ result = runner.invoke(cmd, ['--help'])200+ assert result.exit_code == 0201+ assert '--username' in result.output202+ assert 'lambda' not in result.output203+ assert '(current user)' in result.output204+205 def test_nargs_envvar(runner):206 @click.command()207 @click.option('--arg', nargs=2)208 def cmd(arg):119 unmodified lines328 assert ' --foo TEXT hello' in out329 assert ' i am' in out330 assert ' multiline' in out331 305-332 def test_argument_custom_class(runner):333 class CustomArgument(click.Argument):334 def get_default(self, ctx):335 '''a dumb override of a default value for testing'''107 unmodified linesmodified:setup.py+10 added-4 removed
22 unmodified lines23 maintainer='Pallets team',24 maintainer_email='contact@palletsprojects.com',25 long_description=readme,26 packages=['click'],27+ description='A simple wrapper around optparse for '28+ 'powerful command line utilities.',29+ license='BSD',30 extras_require={28- 'docs': [31+ 'dev': [32+ 'pytest>=3',33+ 'coverage',34+ 'tox',35 'sphinx',36 ],37+ 'docs': [38+ 'sphinx',39+ ]40 },32- description='A simple wrapper around optparse for '33- 'powerful command line utilities.',34- license='BSD',41 classifiers=[42 'Development Status :: 5 - Production/Stable',43 'Intended Audience :: Developers',44 'License :: OSI Approved :: BSD License',11 unmodified lines