Skip to content
Myr

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

5 files+159 added−5 removed

modified:click/__init__.py+1 added-1 removed
12 unmodified lines
13"""1415# Core classes16from .core import Context, BaseCommand, Command, MultiCommand, Group, \17 CommandCollection, Parameter, Option, Argument17 CommandCollection, Parameter, Option, Argument, ParameterSource1819# Globals20from .globals import get_current_context21
76 unmodified lines
modified:click/core.py+67 added-1 removed
127 unmodified lines
128 return (not item.is_eager, idx)129130 return sorted(declaration_order, key=sort_key)131132class ParameterSource(object):133 """This is an enum that indicates the source of a command line parameter.134135 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 """140141 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.151152 This method will raise a ValueError if the value is153 not a valid enum.154155 :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)))160161162class 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 lines
367 self.color = color368369 self._close_callbacks = []370 self._depth = 0371 self._source_by_paramname = {}342372 373 def __enter__(self):374 self._depth += 1375 push_context(self)376 return self
224 unmodified lines
601 kwargs[param] = self.params[param]602603 return self.invoke(cmd, **kwargs)604605 def set_parameter_source(self, name, source):606 """Set the source of a parameter.607608 This indicates the location from which the value of the609 parameter was obtained.610611 :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] = source617618 def get_parameter_source(self, name):619 """Get the source of a parameter.620621 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.627628 :param name: the name of the command line parameter629 :returns: the source630 :rtype: ParameterSource631 """632 return self._source_by_paramname[name]633634635class 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 alternative
813 unmodified lines
1452 pass14531454 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 value14661467 def type_cast_value(self, ctx, value):1468 """Given a value this runs it properly through the type system.
38 unmodified lines
1507 value = self.process_value(ctx, value)15081509 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)15131514 if self.required and self.value_is_missing(value):1515 raise MissingParameter(ctx=ctx, param=self)1516
411 unmodified lines
modified:docs/advanced.rst+27 added
375 unmodified lines
376do. However if you do use this for threading you need to be very careful377as the vast majority of the context is not thread safe! You are only378allowed to read from the context, but not to perform any modifications on379it.380381382Detecting the Source of a Parameter383-----------------------------------384385In some situations it's helpful to understand whether or not an option386or parameter came from the command line, the environment, the default387value, or the default_map. The :meth:`Context.get_parameter_source`388method can be used to find this out.389390.. click:example::391392 @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))398399.. click:run::400401 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 -*-2import click3import pytest445def test_ensure_context_objects(runner):6 class Foo(object):7 def __init__(self):8 self.title = 'default'
246 unmodified lines
255 def cli(ctx):256 ctx.exit(0)257258 assert cli.main([], 'test_exit_not_standalone', standalone_mode=False) == 0259260def 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)267268 assert cli.main([], "test_parameter_source_default", standalone_mode=False) == 1269270def 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)277278 assert cli.main([], "test_parameter_source_default", standalone_mode=False, default_map={ "option": 1}) == 1279 280281def 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) == 1291292293def 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 == 1302303304def 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 == 1313314315def 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 lines
67Unreleased89- 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`_)1011 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/1329161417Version 7.118-----------1920Unreleased
633 unmodified lines