Skip to content
Myr

Added support for default overrides. This fixes #42

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 065ce06 · Browse files · 5 files+92 added−6 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+92 added−6 removed

  • tests:+21 added−2 removed
  • other:+71 added−4 removed

5 files+92 added−6 removed

modified:click/core.py+22 added-1 removed
45 unmodified lines
46 variables. If this is `None` then reading47 from environment variables is disabled. This48 does not affect manually set environment49 variables which are always read.50 :param default_map: a dictionary (like object) with default values51 for parameters.52 """5354 def __init__(self, command, parent=None, info_name=None, obj=None,53 auto_envvar_prefix=None):55 auto_envvar_prefix=None, default_map=None):56 #: the parent context or `None` if none exists.57 self.parent = parent58 #: the :class:`Command` for this context.59 self.command = command
13 unmodified lines
73 if obj is None and parent is not None:74 obj = parent.obj75 #: the user object stored.76 self.obj = obj77 #: A dictionary (like object) with defaults for parameters.78 self.default_map = default_map7980 # If there is no envvar prefix yet, but the parent has one and81 # the command on this level has a name, we can expand the envvar82 # prefix automatically.
69 unmodified lines
152 if rv is None:153 self.obj = rv = object_type()154 return rv155156 def lookup_default(self, name):157 """Looks up the default for a parameter name. This by default158 looks into the :attr:`default_map` if available.159 """160 if self.default_map is not None:161 rv = self.default_map.get(name)162 if callable(rv):163 rv = rv()164 return rv165166 def fail(self, message):167 """Aborts the execution of the program with a specific error168 message.169
205 unmodified lines
375 :param parent: the parent context if available.376 :param extra: extra keyword arguments forwarded to the context377 constructor.378 """379 if 'default_map' not in extra:380 default_map = None381 if parent is not None and parent.default_map is not None:382 default_map = parent.default_map.get(info_name)383 extra['default_map'] = default_map384 ctx = Context(self, info_name=info_name, parent=parent, **extra)385 parser = self.make_parser(ctx)386 opts, args = parser.parse_args(args=args)387
332 unmodified lines
720721 def consume_value(self, ctx, opts):722 value = opts.get(self.name)723 if value is None:724 value = ctx.lookup_default(self.name)725 if value is None:726 value = self.value_from_envvar(ctx)727 return value728729 def process_value(self, ctx, value):
329 unmodified lines
modified:docs/clickdoctools.py+2 added-3 removed
130 unmodified lines
131 buffer = []132133 def invoke(cmd, args=None, prog_name=None, prog_prefix='python ',134 input=None, terminate_input=False, env=None,135 auto_envvar_prefix=None):135 **extra):136 if env:137 for key, value in sorted(env.items()):138 if ' ' in value:139 value = '"%s"' % value
11 unmodified lines
151 if terminate_input:152 input += '\xff'153 with isolation(input=input, env=env) as output:154 try:155 cmd.main(args=args, prog_name=prog_name,156 auto_envvar_prefix=auto_envvar_prefix)155 cmd.main(args=args, prog_name=prog_name, **extra)156 except SystemExit:157 pass158 buffer.extend(output.getvalue().splitlines())159
96 unmodified lines
modified:docs/commands.rst+47 added
252 unmodified lines
253254 invoke(cli, prog_name='cli', args=['--help'])255256In case a command exists on more than one source, the first source wins.257258Overriding Defaults259-------------------260261By default the default value for a parameter is pulled from the262``default`` flag that is provided when it's defined. But that's not the263only place defaults can be loaded from. The other place is the264:attr:`Context.default_map` (a dictionary) on the context. This allows265defaults to be loaded from a config file to override the regular defaults.266267This is useful if you plug in some commands from another package but268you're not satisfied with the defaults.269270The default map can be nested arbitrarily for each subcommand and be271provided when the script is invoked. Alternatively it can also be272overriden at any point by commands. For instance a toplevel command could273load the defaults from a config file.274275Example usage:276277.. click:example::278279 import click280281 @click.group()282 def cli():283 pass284285 @cli.command()286 @click.option('--port', default=8000)287 def runserver(port):288 click.echo('Serving on http://127.0.0.1:%d/' % port)289290 if __name__ == '__main__':291 cli(default_map={292 'runserver': {293 'port': 5000294 }295 })296297.. click:run::298299 invoke(cli, prog_name='cli', args=['runserver'], default_map={300 'runserver': {301 'port': 5000302 }303 })
modified:tests/conftest.py+3 added-2 removed
116 unmodified lines
117 sys.stderr = old_stderr118 click.termui.visible_prompt_func = old_visible_prompt_func119 click.termui.hidden_prompt_func = old_hidden_prompt_func120121 def invoke(self, cli, args):121 def invoke(self, cli, args, **extra):122 with self.isolation() as out:123 exception = None124 exit_code = 0125126 try:127 cli.main(args=args, prog_name=cli.name or 'root')127 cli.main(args=args, prog_name=cli.name or 'root',128 **extra)129 except SystemExit as e:130 if e.code != 0:131 exception = e132 exit_code = e.code
26 unmodified lines
modified:tests/test_commands.py+18 added
36 unmodified lines
37 assert re.search(38 r'Commands:\n\s+'39 r'long\s+This is a long text that is too long to show\.\.\.\n\s+'40 r'short\s+This is a short text\.', result.output) is not None414243def test_default_maps(runner):44 @click.group()45 def cli():46 pass4748 @cli.command()49 @click.option('--name', default='normal')50 def foo(name):51 click.echo(name)5253 result = runner.invoke(cli, ['foo'], default_map={54 'foo': {'name': 'changed'}55 })5657 assert not result.exception58 assert result.output == 'changed\n'