Merge pull request #1329 from joshuastorck/PR-1264
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Adding support to the context to distinguish the source of a command line parameter
authored by David Lord · committed by GitHub · parents 0b1e32b, c296d44 · Browse files · 5 files·+159 added−5 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+159 added−5 removed
- tests:+60 added−1 removed
- other:+99 added−4 removed
Provenance
- Commit
91e5bc3- Tree
fa48f9e- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
0b1e32b- Parent 2
c296d44
5 files changed+159 added−5 removed
modified:click/__init__.py+1 added-1 removed
12 unmodified lines13 """14 15 # Core classes16 from .core import Context, BaseCommand, Command, MultiCommand, Group, \17- CommandCollection, Parameter, Option, Argument17+ CommandCollection, Parameter, Option, Argument, ParameterSource18 19 # Globals20 from .globals import get_current_context21 76 unmodified linesmodified:click/core.py+67 added-1 removed
127 unmodified lines128 return (not item.is_eager, idx)129 130 return sorted(declaration_order, key=sort_key)131 132+class ParameterSource(object):133+ """This is an enum that indicates the source of a command line parameter.134 135+ The enum has one of the following values: COMMANDLINE,136+ ENVIRONMENT, DEFAULT, DEFAULT_MAP. The DEFAULT indicates that the137+ default value in the decorator was used. This class should be138+ converted to an enum when Python 2 support is dropped.139+ """140+141+ COMMANDLINE = "COMMANDLINE"142+ ENVIRONMENT = "ENVIRONMENT"143+ DEFAULT = "DEFAULT"144+ DEFAULT_MAP = "DEFAULT_MAP"145+ 146+ VALUES = {COMMANDLINE, ENVIRONMENT, DEFAULT, DEFAULT_MAP}147+ 148+ @classmethod149+ def validate(cls, value):150+ """Validate that the specified value is a valid enum.151+152+ This method will raise a ValueError if the value is153+ not a valid enum.154+155+ :param value: the string value to verify156+ """157+ if value not in cls.VALUES:158+ raise ValueError("Invalid ParameterSource value: '{}'. Valid "159+ "values are: {}".format(value, ",".join(cls.VALUES)))160+161+162 class Context(object):163 """The context is a special internal object that holds state relevant164 for the script execution at every single level. It's normally invisible165 to commands unless they opt-in to getting access to it.201 unmodified lines367 self.color = color368 369 self._close_callbacks = []370 self._depth = 0371+ self._source_by_paramname = {}342-372+ 373 def __enter__(self):374 self._depth += 1375 push_context(self)376 return self224 unmodified lines601 kwargs[param] = self.params[param]602 603 return self.invoke(cmd, **kwargs)604 605+ def set_parameter_source(self, name, source):606+ """Set the source of a parameter.607 608+ This indicates the location from which the value of the609+ parameter was obtained.610+611+ :param name: the name of the command line parameter612+ :param source: the source of the command line parameter, which613+ should be a valid ParameterSource value614+ """615+ ParameterSource.validate(source)616+ self._source_by_paramname[name] = source617+618+ def get_parameter_source(self, name):619+ """Get the source of a parameter.620+621+ This indicates the location from which the value of the622+ parameter was obtained. This can be useful for determining623+ when a user specified an option on the command line that is624+ the same as the default. In that case, the source would be625+ ParameterSource.COMMANDLINE, even though the value of the626+ parameter was equivalent to the default.627+628+ :param name: the name of the command line parameter629+ :returns: the source630+ :rtype: ParameterSource631+ """632+ return self._source_by_paramname[name]633+634+635 class BaseCommand(object):636 """The base command implements the minimal API contract of commands.637 Most code will never use this as it does not implement a lot of useful638 functionality but it can act as the direct subclass of alternative813 unmodified lines1452 pass1453 1454 def consume_value(self, ctx, opts):1455 value = opts.get(self.name)1456+ source = ParameterSource.COMMANDLINE1457 if value is None:1458 value = self.value_from_envvar(ctx)1459+ source = ParameterSource.ENVIRONMENT1460 if value is None:1461 value = ctx.lookup_default(self.name)1462+ source = ParameterSource.DEFAULT_MAP1463+ if value is not None:1464+ ctx.set_parameter_source(self.name, source)1465 return value1466 1467 def type_cast_value(self, ctx, value):1468 """Given a value this runs it properly through the type system.38 unmodified lines1507 value = self.process_value(ctx, value)1508 1509 if value is None and not ctx.resilient_parsing:1510 value = self.get_default(ctx)1511+ if value is not None:1512+ ctx.set_parameter_source(self.name, ParameterSource.DEFAULT)1513 1514 if self.required and self.value_is_missing(value):1515 raise MissingParameter(ctx=ctx, param=self)1516 411 unmodified linesmodified:docs/advanced.rst+27 added
375 unmodified lines376 do. However if you do use this for threading you need to be very careful377 as the vast majority of the context is not thread safe! You are only378 allowed to read from the context, but not to perform any modifications on379 it.380+381+382+Detecting the Source of a Parameter383+-----------------------------------384+385+In some situations it's helpful to understand whether or not an option386+or parameter came from the command line, the environment, the default387+value, or the default_map. The :meth:`Context.get_parameter_source`388+method can be used to find this out.389+390+.. click:example::391+392+ @click.command()393+ @click.argument('port', nargs=1, default=8080, envvar="PORT")394+ @click.pass_context395+ def cli(ctx, port):396+ source = ctx.get_parameter_source("port")397+ click.echo("Port came from {}".format(source))398+399+.. click:run::400+401+ invoke(cli, prog_name='cli', args=['8080'])402+ println()403+ invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"})404+ println()405+ invoke(cli, prog_name='cli', args=[])406+ println()modified:tests/test_context.py+60 added-1 removed
1 # -*- coding: utf-8 -*-2 import click3+import pytest4 4-5 def test_ensure_context_objects(runner):6 class Foo(object):7 def __init__(self):8 self.title = 'default'246 unmodified lines255 def cli(ctx):256 ctx.exit(0)257 258 assert cli.main([], 'test_exit_not_standalone', standalone_mode=False) == 0259+260+def test_parameter_source_default():261+ @click.command()262+ @click.pass_context263+ @click.option("-o", "--option", default=1)264+ def cli(ctx, option):265+ assert ctx.get_parameter_source("option") == click.ParameterSource.DEFAULT266+ ctx.exit(1)267+268+ assert cli.main([], "test_parameter_source_default", standalone_mode=False) == 1269+270+def test_parameter_source_default_map():271+ @click.command()272+ @click.pass_context273+ @click.option("-o", "--option", default=1)274+ def cli(ctx, option):275+ assert ctx.get_parameter_source("option") == click.ParameterSource.DEFAULT_MAP276+ ctx.exit(1)277+278+ assert cli.main([], "test_parameter_source_default", standalone_mode=False, default_map={ "option": 1}) == 1279+ 280+281+def test_parameter_source_commandline():282+ @click.command()283+ @click.pass_context284+ @click.option("-o", "--option", default=1)285+ def cli(ctx, option):286+ assert ctx.get_parameter_source("option") == click.ParameterSource.COMMANDLINE287+ ctx.exit(1)288+ 289+ assert cli.main(["-o", "1"], "test_parameter_source_commandline", standalone_mode=False) == 1290+ assert cli.main(["--option", "1"], "test_parameter_source_default", standalone_mode=False) == 1291+292+293+def test_parameter_source_environment(runner):294+ @click.command()295+ @click.pass_context296+ @click.option("-o", "--option", default=1)297+ def cli(ctx, option):298+ assert ctx.get_parameter_source("option") == click.ParameterSource.ENVIRONMENT299+ sys.exit(1)300+ 301+ assert runner.invoke(cli, [], prog_name="test_parameter_source_environment", env={"TEST_OPTION": "1"}, auto_envvar_prefix="TEST").exit_code == 1302+303+304+def test_parameter_source_environment_variable_specified(runner):305+ @click.command()306+ @click.pass_context307+ @click.option("-o", "--option", default=1, envvar="NAME")308+ def cli(ctx, option):309+ assert ctx.get_parameter_source("option") == click.ParameterSource.ENVIRONMENT310+ sys.exit(1)311+ 312+ assert runner.invoke(cli, [], prog_name="test_parameter_source_environment", env={"NAME": "1"}).exit_code == 1313+314+315+def test_validate_parameter_source():316+ with pytest.raises(ValueError):317+ click.ParameterSource.validate("NOT_A_VALID_PARAMETER_SOURCE")modified:CHANGES.rst+4 added-2 removed
5 unmodified lines6 7 Unreleased8 9 - Adds a repr to Command, showing the command name for friendlier debugging. (`#1267`_, `#1295`_)10+- Add support for distinguishing the source of a command line parameter. (`#1264`_, `#1329`_)10-11+ 12 .. _#1267: https://github.com/pallets/click/issues/126713 .. _#1295: https://github.com/pallets/click/pull/129514+.. _#1264: https://github.com/pallets/click/issues/126415+.. _#1329: https://github.com/pallets/click/pull/132916 14-17 Version 7.118 -----------19 20 Unreleased633 unmodified lines