aiida.cmdline.params.options package#
Module with pre-defined reusable commandline options that can be used as click decorators.
Submodules#
Option whose requiredness is determined by a callback function.
- class aiida.cmdline.params.options.conditional.ConditionalOption(param_decls=None, required_fn=None, **kwargs)[source]#
Bases:
click.core.Option
Option whose requiredness is determined by a callback function.
This option takes an additional callable parameter
required_fn
and uses that to determine whether aMissingParameter
exception should be raised if no value is specified for the parameters.The callable should take the context as an argument which it can use to inspect the value of other parameters that have been passed to the command invocation.
- 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.
- __module__ = 'aiida.cmdline.params.options.conditional'#
The functions configuration_callback()
and configuration_option()
were directly taken from the repository
phha/click_config_file with a
minor modification to configuration_callback
to add a check for unknown parameters in the configuration file and
the default provider is changed to yaml_config_file_provider()
.
- class aiida.cmdline.params.options.config.ConfigFileOption(*args, **kwargs)[source]#
Bases:
aiida.cmdline.params.options.overridable.OverridableOption
Reusable option that reads a configuration file containing values for other command parameters.
Example:
CONFIG_FILE = ConfigFileOption('--config', help='A configuration file') @click.command() @click.option('computer_name') @CONFIG_FILE(help='Configuration file for computer_setup') def computer_setup(computer_name): click.echo(f"Setting up computer {computername}") computer_setup --config config.yml
with config.yml:
--- computer_name: computer1
- __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_config_file.configuration_option constructed with args and kwargs defined during construction and call of this instance
- __init__(*args, **kwargs)[source]#
Store the default args and kwargs.
- Parameters
args – default arguments to be used for the option
kwargs – default keyword arguments to be used that can be overridden in the call
- __module__ = 'aiida.cmdline.params.options.config'#
- aiida.cmdline.params.options.config.configuration_callback(cmd_name: str | None, option_name: str, config_file_name: str, saved_callback: Optional[Callable[[...], Any]], provider: Callable[[...], Any], implicit: bool, ctx: click.core.Context, param: click.core.Parameter, value: Any)[source]#
Callback for reading the config file.
Also takes care of calling user specified custom callback afterwards.
- Parameters
cmd_name – The command name. This is used to determine the configuration directory.
option_name – The name of the option. This is used for error messages.
config_file_name – The name of the configuration file.
saved_callback – User-specified callback to be called later.
provider – A callable that parses the configuration file and returns a dictionary of the configuration parameters. Will be called as
provider(file_path, cmd_name)
. Default:yaml_config_file_provider
.implicit – Whether a implicit value should be applied if no configuration option value was provided.
ctx –
click
context.param –
click
parameters.value – Value passed to the parameter.
- aiida.cmdline.params.options.config.configuration_option(*param_decls, **attrs)[source]#
Adds configuration file support to a click application.
This will create an option of type
click.File
expecting the path to a configuration file. When specified, it overwrites the default values for all other click arguments or options with the corresponding value from the configuration file. The default name of the option is--config
. By default, the configuration will be read from a configuration directory as determined byclick.get_app_dir
. This decorator accepts the same arguments asclick.option
andclick.Path
. In addition, the following keyword arguments are available:- Parameters
cmd_name – str The command name. This is used to determine the configuration directory. Default:
ctx.info_name
.config_file_name – str The name of the configuration file. Default:
config
.implicit – bool If
True
then implicitly create a value for the configuration option using the above parameters. If a configuration file exists in this path it will be applied even if no configuration option was suppplied as a CLI argument or environment variable. IfFalse
only apply a configuration file that has been explicitely specified. Default:False
.provider – callable A callable that parses the configuration file and returns a dictionary of the configuration parameters. Will be called as
provider(file_path, cmd_name)
. Default:yaml_config_file_provider
.
- aiida.cmdline.params.options.config.yaml_config_file_provider(handle, cmd_name)[source]#
Read yaml config file from file handle.
- class aiida.cmdline.params.options.interactive.InteractiveOption(param_decls=None, prompt_fn=None, contextual_default=None, **kwargs)[source]#
Bases:
aiida.cmdline.params.options.conditional.ConditionalOption
Prompts for input, intercepting certain keyword arguments to replace
click
’s prompting behaviour with a more feature-rich one.Note
This class has a parameter
required_fn
that can be passed to its__init__
(inherited from the superclassConditionalOption
) and aprompt_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 inConditionalOption
.
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(f'Labeling with label: {label}')
- CHARACTER_IGNORE_DEFAULT = '!'#
- CHARACTER_PROMPT_HELP = '?'#
- PROMPT_COLOR = 'bright_yellow'#
- __annotations__ = {'default': 't.Union[t.Any, t.Callable[[], t.Any]]', 'flag_value': 't.Any', 'is_bool_flag': 'bool', 'is_flag': 'bool', 'name': 't.Optional[str]', 'opts': 't.List[str]', 'secondary_opts': 't.List[str]', 'type': 'types.ParamType'}#
- __init__(param_decls=None, prompt_fn=None, contextual_default=None, **kwargs)[source]#
- Parameters
param_decls – relayed to
click.Option
prompt_fn – callable(ctx) -> Bool, 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: click.core.Context, call: bool = True) Optional[Union[Any, Callable[[], Any]]] [source]#
provides the functionality of
click.Option.get_default()
- static is_interactive(ctx: click.core.Context) bool [source]#
Return whether the command is being run non-interactively.
This is the case if the
non_interactive
parameter in the context is set toTrue
.- Returns
True
if being run non-interactively,False
otherwise.
- process_value(ctx: click.core.Context, value: Any) Any [source]#
Intercept any special characters before calling parent class if in interactive mode.
If the value matches
CHARACTER_PROMPT_HELP
, echoget_help_message
and reprompt.If the value matches
CHARACTER_IGNORE_DEFAULT
, ignore the value and returnNone
.
Note that this logic only applies if the value is specified at the prompt, if it is provided from the command line, the value is actually taken as the value and processed as normal. To determine how the parameter was specified the
click.Context.get_parameter_source
method is used. Theclick.Parameter.handle_parse_result
method will set this afterParameter.consume_value`
is called but beforeParameter.process_value
is.
- property prompt#
Return a colorized version of the prompt text.
- prompt_for_value(ctx: click.core.Context) Any [source]#
Prompt for a value printing a generic help message if this is the first invocation of the command.
If the command is invoked in non-interactive mode, meaning one should never prompt for a value, the default is returned instead of prompting.
If the help message is printed, the
prompt_loop_info_printed
variable is set in the context which is used to check whether the message has already been printed as to only print it once at the first prompt.
- class aiida.cmdline.params.options.interactive.TemplateInteractiveOption(param_decls=None, **kwargs)[source]#
Bases:
aiida.cmdline.params.options.interactive.InteractiveOption
Sub class of
InteractiveOption
that uses template file for input instead of simple inline prompt.This is useful for options that need to be able to specify multiline string values.
- __annotations__ = {}#
- __init__(param_decls=None, **kwargs)[source]#
Define the configuration for the multiline template in the keyword arguments.
- Parameters
template – name of the template to use from the
aiida.cmdline.templates
directory. Default is the ‘multiline.tpl’ template.header – string to put in the header of the template.
footer – string to put in the footer of the template.
extension – file extension to give to the template file.
- __module__ = 'aiida.cmdline.params.options.interactive'#
- prompt_for_value(ctx: click.core.Context) Any [source]#
Replace the basic prompt with a method that opens a template file in an editor.
Module with pre-defined reusable commandline options that can be used as click decorators.
- aiida.cmdline.params.options.main.active_process_states()[source]#
Return a list of process states that are considered active.
- aiida.cmdline.params.options.main.graph_traversal_rules(rules)[source]#
Apply the graph traversal rule options to the command.
- aiida.cmdline.params.options.main.set_log_level(_ctx, _param, value)[source]#
Configure the logging for the CLI command being executed.
Note that we cannot use the most obvious approach of directly setting the level on the various loggers. The reason is that after this callback is finished, the
aiida.common.log.configure_logging()
method can be called again, for example when the database backend is loaded, and this will undo this change. So instead, we set to globals in theaiida.common.log
module:CLI_ACTIVE
andCLI_LOG_LEVEL
. TheCLI_ACTIVE
global is always set toTrue
. Theconfigure_logging
function will interpret this as the code being executed through averdi
call. TheCLI_LOG_LEVEL
global is only set if an explicit value is set for the--verbosity
option. In this case, it is set to the specified log level andconfigure_logging
will then set this log level for all loggers.This approach tightly couples the generic
aiida.common.log
module to theaiida.cmdline
module, which is not the cleanest, but given that other module code can undo the logging configuration by calling that method, there seems no easy way around this approach.
- aiida.cmdline.params.options.main.valid_calc_job_states()[source]#
Return a list of valid values for the CalcState enum.
- aiida.cmdline.params.options.main.valid_process_states()[source]#
Return a list of valid values for the ProcessState enum.
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- __annotations__ = {}#
- __module__ = 'aiida.cmdline.params.options.multivalue'#
- aiida.cmdline.params.options.multivalue.collect_usage_pieces(self, ctx)[source]#
Returns all the pieces that go into the usage line and returns it as a list of strings.
- 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))
- __annotations__ = {}#
- __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__ = mappingproxy({'__module__': 'aiida.cmdline.params.options.overridable', '__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 OverridableOption.__init__>, '__call__': <function OverridableOption.__call__>, 'clone': <function OverridableOption.clone>, '__dict__': <attribute '__dict__' of 'OverridableOption' objects>, '__weakref__': <attribute '__weakref__' of 'OverridableOption' objects>, '__slotnames__': [], '__annotations__': {}})#
- __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'#
- __slotnames__ = []#
- __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