aiida.cmdline.params.options package

Module with pre-defined reusable commandline options that can be used as click decorators.

Submodules

class aiida.cmdline.params.options.conditional.ConditionalOption(param_decls=None, required_fn=None, **kwargs)[source]

Bases: click.core.Option

This cli option takes an additional callable parameter and uses that to determine wether a MissingParam should be raised if the option is not given on the cli.

The callable takes the context as an argument and can look up any amount of other parameter values etc.

Parameters:required_fn – callable(ctx) -> True | False, returns True if the parameter is required to have a value. This is typically used when the condition depends on other parameters specified on the command line.
__init__(param_decls=None, required_fn=None, **kwargs)[source]

x.__init__(…) initializes x; see help(type(x)) for signature

__module__ = 'aiida.cmdline.params.options.conditional'
full_process_value(ctx, value)[source]
is_required(ctx)[source]

runs the given check on the context to determine requiredness

class aiida.cmdline.params.options.interactive.InteractiveOption(param_decls=None, switch=None, prompt_fn=None, contextual_default=None, **kwargs)[source]

Bases: aiida.cmdline.params.options.conditional.ConditionalOption

Intercepts certain keyword arguments to circumvent click’s prompting behaviour and define a more feature-rich one

Note

This class has a parameter required_fn that can be passed to its __init__ (inherited from the superclass ConditionalOption) and a prompt_fn.

  • required_fn is about “is this parameter required” depending on the value of other params.
  • prompt_fn is about “should I prompt for this value if in interactive mode” and only makes sense in this class and not in ConditionalOption.

In most usecases, if I have a prompt_fn, then I would like to have also (the same) required_fn. The implementation still makes them independent for usecases where they might be different functions (e.g. if the variable is anyway not required, but you want to decide whether to prompt for it or not).

Usage:

import click

@click.command()
@click.option('label', prompt='Label', cls=InteractiveOption)
def foo(label):
    click.echo('Labeling with label: {}'.format(label))
PROMPT_COLOR = 'yellow'
__init__(param_decls=None, switch=None, prompt_fn=None, contextual_default=None, **kwargs)[source]
Parameters:
  • param_decls – relayed to click.Option
  • switch – sequence of parameter
  • prompt_fn – callable(ctx) -> True | False, returns True if the option should be prompted for in interactive mode.
  • contextual_default – An optional callback function to get a default which is passed the click context
__module__ = 'aiida.cmdline.params.options.interactive'
_get_default(ctx)[source]

provides the functionality of click.Option.get_default()

after_callback(ctx, param, value)[source]

if a callback was registered on init, call it and return it’s value

ctrl_help()[source]

control behaviour when help is requested from the prompt

static custom_value_proc(value)[source]

Custom value_proc function for the click.prompt which it will call to do value conversion.

Simply return the value, because we want to take care of value conversion ourselves in the simple_prompt_loop. If we let click.prompt do it, it will raise an exception when the user passes a control character, like the question mark, to bring up the help message and the type of the option is not a string, causing conversion to fail.

format_help_message()[source]

format the message to be displayed for in-prompt help.

gives a list of possibilities for parameter types that support completion

full_process_value(ctx, value)[source]

catch errors raised by ConditionalOption in order to adress them in the callback

get_default(ctx)[source]

disable click from circumventing prompting when a default value exists

prompt_callback(ctx, param, value)[source]

decide wether to initiate the prompt_loop or not

prompt_func(ctx)[source]

prompt function with args set

safely_convert(value, param, ctx)[source]

convert without raising, instead print a message if fails

Returns:Tuple of ( success (bool), converted value )
simple_prompt_loop(ctx, param, value)[source]

prompt until successful conversion. dispatch control sequences

aiida.cmdline.params.options.interactive.noninteractive(ctx)[source]

check context for non_interactive flag

aiida.cmdline.params.options.interactive.opt_prompter(ctx, cmd, givenkwargs, oldvalues=None)[source]

Prompt interactively for the value of an option of the command with context ctx.

Used to produce more complex behaviours than can be achieved with InteractiveOption alone.

aiida.cmdline.params.options.interactive.string_wrapper(msg, max_length=100)[source]

Wraps a string into multiple lines according to max_length

Module to define multi value options for click.

class aiida.cmdline.params.options.multivalue.MultipleValueOption(*args, **kwargs)[source]

Bases: click.core.Option

An option that can handle multiple values with a single flag. For example:

@click.option('-n', '--nodes', cls=MultipleValueOption)

Will be able to parse the following:

--nodes 10 15 12

This is better than the builtin multiple=True keyword for click’s option which forces the user to specify the option flag for each value, which gets impractical for long lists of values

__init__(*args, **kwargs)[source]

x.__init__(…) initializes x; see help(type(x)) for signature

__module__ = 'aiida.cmdline.params.options.multivalue'
add_to_parser(parser, ctx)[source]

Override built in click method that allows us to specify a custom parser to eat up parameters until the following flag or ‘endopt’ (i.e. –)

class aiida.cmdline.params.options.overridable.OverridableOption(*args, **kwargs)[source]

Bases: object

Wrapper around click option that increases reusability

Click options are reusable already but sometimes it can improve the user interface to for example customize a help message for an option on a per-command basis. Sometimes the option should be prompted for if it is not given On some commands an option might take any folder path, while on another the path only has to exist.

Overridable options store the arguments to click.option and only instantiate the click.Option on call, kwargs given to __call__ override the stored ones.

Example:

FOLDER = OverridableOption('--folder', type=click.Path(file_okay=False), help='A folder')

@click.command()
@FOLDER(help='A folder, will be created if it does not exist')
def ls_or_create(folder):
    click.echo(os.listdir(folder))

@click.command()
@FOLDER(help='An existing folder', type=click.Path(exists=True, file_okay=False, readable=True)
def ls(folder)
    click.echo(os.listdir(folder))
__call__(**kwargs)[source]

Override the stored kwargs, (ignoring args as we do not allow option name changes) and return the option.

Parameters:kwargs – keyword arguments that will override those set in the construction
Returns:click option constructed with args and kwargs defined during construction and call of this instance
__dict__ = dict_proxy({'__module__': 'aiida.cmdline.params.options.overridable', 'clone': <function clone>, '__dict__': <attribute '__dict__' of 'OverridableOption' objects>, '__call__': <function __call__>, '__weakref__': <attribute '__weakref__' of 'OverridableOption' objects>, '__doc__': "\n Wrapper around click option that increases reusability\n\n Click options are reusable already but sometimes it can improve the user interface to for example customize a\n help message for an option on a per-command basis. Sometimes the option should be prompted for if it is not given\n On some commands an option might take any folder path, while on another the path only has to exist.\n\n Overridable options store the arguments to click.option and only instantiate the click.Option on call,\n kwargs given to ``__call__`` override the stored ones.\n\n Example::\n\n FOLDER = OverridableOption('--folder', type=click.Path(file_okay=False), help='A folder')\n\n @click.command()\n @FOLDER(help='A folder, will be created if it does not exist')\n def ls_or_create(folder):\n click.echo(os.listdir(folder))\n\n @click.command()\n @FOLDER(help='An existing folder', type=click.Path(exists=True, file_okay=False, readable=True)\n def ls(folder)\n click.echo(os.listdir(folder))\n ", '__init__': <function __init__>})
__init__(*args, **kwargs)[source]

Store the default args and kwargs.

Parameters:
  • args – default arguments to be used for the click option
  • kwargs – default keyword arguments to be used that can be overridden in the call
__module__ = 'aiida.cmdline.params.options.overridable'
__weakref__

list of weak references to the object (if defined)

clone(**kwargs)[source]

Create a new instance of the OverridableOption by cloning it and updating the stored kwargs with those passed.

This can be useful when an already predefined OverridableOption needs to be further specified and reused by a set of sub commands. Example:

LABEL = OverridableOption('-l', '--label', required=False, help='The label of the node'
LABEL_COMPUTER = LABEL.clone(required=True, help='The label of the computer')

If multiple computer related sub commands need the LABEL option, but the default help string and required attribute need to be different, the clone method allows to override these and create a new OverridableOption instance that can then be used as a decorator.

Parameters:kwargs – keyword arguments to update
Returns:OverridableOption instance with stored keyword arguments updated

Unit tests for the ConditionalOption.

class aiida.cmdline.params.options.test_conditional.ConditionalOptionTest(methodName='runTest')[source]

Bases: unittest.case.TestCase

Unit tests for ConditionalOption.

__module__ = 'aiida.cmdline.params.options.test_conditional'
classmethod setUpClass()[source]

Hook method for setting up class fixture before running tests in the class.

static setup_flag_cond(**kwargs)[source]

Set up a command with a flag and a customizable option that depends on it.

setup_multi_non_eager()[source]

scenario a-or-b:

  • flag a_or_b (–a/–b)
  • opt-a required if a_or_b == True
  • opt-b required if a_or_b == False
simple_cmd(pname, required_fn=<function <lambda>>, **kwargs)[source]

returns a command with two options:

  • an option created from the args and kwargs
  • –opt, ConditionalOption with required_fn from kwargs
test_aa()[source]

scenario = a-or-b action: require a, give a (+ reversed order) behaviour: command runs

test_ab()[source]

scenario = a-or-b action: require a, give b (+ reversed order) behaviour: fail, Missing option

test_ba()[source]

scenario = a-or-b action: require b, give a (+ reversed order) behaviour: fail, Missing option

test_callback()[source]

Test that the callback still gets called.

test_default()[source]

Test that the default still gets passed.

test_flag_off()[source]

scenario: flag “–on” detrmines if option opt is required action: invoke without options behaviour: command runs without complaining

test_flag_on()[source]

scenario: flag “–on” detrmines if option opt is required action: invoke with –on behaviour: fails with Missing option message

test_prompt_callback()[source]

Test that the callback gets called on prompt results.

test_required()[source]

Test that required_fn overrides required if it evaluates to False.

test_switch_off()[source]

scenario: switch –on/–off detrmines if option opt is required action: invoke with no options behaviour: flag is off by default -> command runs without complaining

test_switch_on()[source]

scenario: switch –on/–off detrmines if option opt is required action: invoke with –on behaviour: fails with Missin option message

static user_callback(_ctx, param, value)[source]

Testing callback that does not accept 42 and transforms a missing value to -1

Unit tests for the InteractiveOption.

class aiida.cmdline.params.options.test_interactive.InteractiveOptionTest(methodName='runTest')[source]

Bases: unittest.case.TestCase

Unit tests for InteractiveOption.

__module__ = 'aiida.cmdline.params.options.test_interactive'
prompt_output(cli_input, converted=None)[source]

Return expected output of simple_command, given a commandline cli_input string.

classmethod setUpClass()[source]

Hook method for setting up class fixture before running tests in the class.

simple_command(**kwargs)[source]

Return a simple command with one InteractiveOption, kwargs get relayed to the option.

static strip_line(text)[source]

returns text without the last line

test_after_callback_default_noninteractive()[source]

Test that the callback gets called on the default, in line with click 6 behaviour.

Scenario:
  • InteractiveOption with user callback and invalid default
  • invoke with no options and –non-interactive
Behaviour:
  • the default value gets passed through the callback and rejected
test_after_callback_empty()[source]

scenario: InteractiveOption with a user callback action: invoke with invalid value of wrong type behaviour: user callback does not run

test_after_callback_invalid()[source]

scenario: InteractiveOption with a user callback action: invoke with invalid value of right type behaviour: user callback runs & succeeds

test_after_callback_valid()[source]

scenario: InteractiveOption with a user callback action: invoke with valid value behaviour: user callback runs & succeeds

test_after_callback_wrong_typ()[source]

scenario: InteractiveOption with a user callback action: invoke with invalid value of wrong type behaviour: user callback does not run

test_after_validation_interactive()[source]

Test that the type validation gets called on values entered at a prompt.

Scenario:
  • InteractiveOption with custom type and prompt set
  • invoked without passing the options
  • on prompt: first enter an invalid value, then a valid one
Behaviour:
  • Prompt for the value
  • reject invalid value, prompt again
  • accept valid value
test_default_empty_empty_cli()[source]

Test that default=”” allows to pass an empty cli option.

test_default_empty_prompt()[source]

Test that default=”” allows to pass an empty cli option.

test_default_value_empty_opt()[source]

scenario: InteractiveOption with default value, invoke with empty option (–opt=) behaviour: accept empty string as input

test_default_value_prompt()[source]

scenario: using InteractiveOption with a default value, invoke without options behaviour: prompt, showing the default value, take default on empty cli_input.

test_non_interactive()[source]

scenario: InteractiveOption, invoked with only –non-interactive (and the option is required) behaviout: fail

test_non_interactive_default()[source]

scenario: InteractiveOption, invoked with only –non-interactive behaviour: fail

test_not_required_interactive()[source]
test_not_required_interactive_default()[source]
test_not_required_noninteractive()[source]
test_not_required_noninteractive_default()[source]
test_opt_given_invalid()[source]

scenario: InteractiveOption, invoked with a valid value on the cmdline behaviour: accept valid value

test_opt_given_valid()[source]

scenario: InteractiveOption, invoked with a valid value on the cmdline behaviour: accept valid value

test_prompt_complex()[source]

scenario: using InteractiveOption with type=float behaviour: giving no option prompts, accepts 3.14e-7

test_prompt_dynamic_default()[source]

Test that dynamic defaults for prompting still work.

test_prompt_empty_input()[source]

scenario: using InteractiveOption with type=str and invoking without options behaviour: pressing enter on empty line at prompt repeats the prompt without a message

test_prompt_help_custom()[source]

scenario: using InteractiveOption with type=str and help message and invoking without options behaviour: entering ‘?’ leads to the given help message being printed and the prompt repeated

test_prompt_help_default()[source]

scenario: using InteractiveOption with type=str and no help parameter and invoking without options behaviour: entering ‘?’ leads to a default help message being printed and prompt repeated

test_prompt_simple()[source]

scenario: using InteractiveOption with type=bool behaviour: giving no option prompts, accepts ‘true’

test_prompt_str()[source]

scenario: using InteractiveOption with type=str behaviour: giving no option prompts, accepts a string

static user_callback(_ctx, param, value)[source]

A fake user callback ued for testing.

Parameters:
  • _ctx – The click context
  • param – The parameter name
  • value – The parameter value
Returns:

The validated parameter

class aiida.cmdline.params.options.test_interactive.Only42IntParamType[source]

Bases: click.types.IntParamType

Param type that only accepts 42 as valid value

__module__ = 'aiida.cmdline.params.options.test_interactive'
__repr__() <==> repr(x)[source]
convert(value, param, ctx)[source]

Converts the value. This is not invoked for values that are None (the missing value).

name = 'only42int'