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
Provenance
- Commit
e77783d- Tree
8ab1a3c- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
065ce06
5 files changed+92 added−6 removed
modified:click/core.py+22 added-1 removed
45 unmodified lines46 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 """53 54 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 = command13 unmodified lines73 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_map79 80 # 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 lines152 if rv is None:153 self.obj = rv = object_type()154 return rv155 156+ 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 rv165+166 def fail(self, message):167 """Aborts the execution of the program with a specific error168 message.169 205 unmodified lines375 :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 lines720 721 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 value728 729 def process_value(self, ctx, value):329 unmodified linesmodified:docs/clickdoctools.py+2 added-3 removed
130 unmodified lines131 buffer = []132 133 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"' % value11 unmodified lines151 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 linesmodified:docs/commands.rst+47 added
252 unmodified lines253 254 invoke(cli, prog_name='cli', args=['--help'])255 256 In case a command exists on more than one source, the first source wins.257+258+Overriding Defaults259+-------------------260+261+By default the default value for a parameter is pulled from the262+``default`` flag that is provided when it's defined. But that's not the263+only place defaults can be loaded from. The other place is the264+:attr:`Context.default_map` (a dictionary) on the context. This allows265+defaults to be loaded from a config file to override the regular defaults.266+267+This is useful if you plug in some commands from another package but268+you're not satisfied with the defaults.269+270+The default map can be nested arbitrarily for each subcommand and be271+provided when the script is invoked. Alternatively it can also be272+overriden at any point by commands. For instance a toplevel command could273+load the defaults from a config file.274+275+Example usage:276+277+.. click:example::278+279+ import click280+281+ @click.group()282+ def cli():283+ pass284+285+ @cli.command()286+ @click.option('--port', default=8000)287+ def runserver(port):288+ click.echo('Serving on http://127.0.0.1:%d/' % port)289+290+ if __name__ == '__main__':291+ cli(default_map={292+ 'runserver': {293+ 'port': 5000294+ }295+ })296+297+.. click:run::298+299+ 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 lines117 sys.stderr = old_stderr118 click.termui.visible_prompt_func = old_visible_prompt_func119 click.termui.hidden_prompt_func = old_hidden_prompt_func120 121- def invoke(self, cli, args):121+ def invoke(self, cli, args, **extra):122 with self.isolation() as out:123 exception = None124 exit_code = 0125 126 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.code26 unmodified linesmodified:tests/test_commands.py+18 added
36 unmodified lines37 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 None41+42+43+def test_default_maps(runner):44+ @click.group()45+ def cli():46+ pass47+48+ @cli.command()49+ @click.option('--name', default='normal')50+ def foo(name):51+ click.echo(name)52+53+ result = runner.invoke(cli, ['foo'], default_map={54+ 'foo': {'name': 'changed'}55+ })56+57+ assert not result.exception58+ assert result.output == 'changed\n'