flexmeasures.cli.utils
Utils for FlexMeasures CLI
Functions
- flexmeasures.cli.utils.add_cli_options_from_schema(schema)
Decorator to add CLI options based on a Marshmallow schema’s fields.
- flexmeasures.cli.utils.are_all_equal(paths: list[list[str]]) bool
Checks if all given entity paths represent the same path.
- flexmeasures.cli.utils.get_sensor_aliases(sensors: list[Sensor], reduce_paths: bool = True, separator: str = '/') dict
Generates aliases for all sensors by appending a unique path to each sensor’s name.
Parameters: :param sensors: A list of Sensor objects. :param reduce_paths: Flag indicating whether to reduce each sensor’s entity path. Defaults to True. :param separator: Character or string used to separate entities within each sensor’s path. Defaults to “/”.
- Returns:
A dictionary mapping sensor IDs to their generated aliases.
- flexmeasures.cli.utils.get_timerange_from_flag(last_hour: bool = False, last_day: bool = False, last_7_days: bool = False, last_month: bool = False, last_year: bool = False, timezone: BaseTzInfo | None = None) tuple[datetime, datetime]
This function returns a time range [start,end] of the last-X period. See input parameters for more details.
- Parameters:
last_hour (bool) – flag to get the time range of the last finished hour.
last_day (bool) – flag to get the time range for yesterday.
last_7_days (bool) – flag to get the time range of the previous 7 days.
last_month (bool) – flag to get the time range of last calendar month
last_year (bool) – flag to get the last completed calendar year
timezone – timezone object to represent
- Returns:
start:datetime, end:datetime
- flexmeasures.cli.utils.path_to_str(path: list, separator: str = '>') str
Converts a list representing a path to a string format, using a specified separator.
- flexmeasures.cli.utils.reduce_entity_paths(asset_paths: list[list[str]]) list[list[str]]
Simplifies a list of entity paths by trimming their common ancestor.
Examples: >>> reduce_entity_paths([[“Account1”, “Asset1”], [“Account2”, “Asset2”]]) [[‘Account1’, ‘Asset1’], [‘Account2’, ‘Asset2’]]
>>> reduce_entity_paths([["Asset1"], ["Asset2"]]) [['Asset1'], ['Asset2']]
>>> reduce_entity_paths([["Account1", "Asset1"], ["Account1", "Asset2"]]) [['Asset1'], ['Asset2']]
>>> reduce_entity_paths([["Asset1", "Asset2"], ["Asset1"]]) [['Asset1', 'Asset2'], ['Asset1']]
>>> reduce_entity_paths([["Account1", "Asset", "Asset1"], ["Account1", "Asset", "Asset2"]]) [['Asset1'], ['Asset2']]
- flexmeasures.cli.utils.split_commas(ctx, param, value)
Converge comma-separated lists of items with a list of unique items.
- flexmeasures.cli.utils.tabulate_account_assets(assets)
Print a tabulated representation of the given assets.
- Args:
assets: an iterable of GenericAsset objects
- flexmeasures.cli.utils.validate_color_cli(ctx, param, value)
Optional parameter validation
Validates that a given value is a valid hex color code.
Parameters: :param ctx: Click context. :param param: Click parameter name. :param value: The color code to validate.
- flexmeasures.cli.utils.validate_unique(ctx, param, value)
Callback function to ensure multiple values are unique.
- flexmeasures.cli.utils.validate_url_cli(ctx, param, value)
Optional parameter validation
Validates that a given value is a valid URL format using regex.
Parameters: :param ctx: Click context. :param param: Click parameter name. :param value: The URL to validate.
Classes
- class flexmeasures.cli.utils.DeprecatedDefaultGroup(*args, **kwargs)
Invokes a default subcommand, and shows a deprecation message.
Also adds the invoked_default boolean attribute to the context. A group callback can use this information to figure out if it’s being executed directly (invoking the default subcommand) or because the execution flow passes onwards to a subcommand. By default it’s None, but it can be the name of the default subcommand to execute.
import click from flexmeasures.cli.utils import DeprecatedDefaultGroup @click.group(cls=DeprecatedDefaultGroup, default="bar", deprecation_message="renamed to `foo bar`.") def foo(ctx): if ctx.invoked_default: click.echo("foo") @foo.command() def bar(): click.echo("bar")
$ flexmeasures foo DeprecationWarning: renamed to `foo bar`. foo bar $ flexmeasures foo bar bar
- __init__(*args, **kwargs)
- get_command(ctx, cmd_name)
Given a context and a command name, this returns a
Commandobject if it exists or returnsNone.
- class flexmeasures.cli.utils.DeprecatedOption(*args, **kwargs)
A custom option that can be used to mark an option as deprecated.
References
Copied from https://stackoverflow.com/a/50402799/13775459
- __init__(*args, **kwargs)
- class flexmeasures.cli.utils.DeprecatedOptionsCommand(name: str | None, context_settings: MutableMapping[str, Any] | None = None, callback: Callable[[...], Any] | None = None, params: list[Parameter] | None = None, help: str | None = None, epilog: str | None = None, short_help: str | None = None, options_metavar: str | None = '[OPTIONS]', add_help_option: bool = True, no_args_is_help: bool = False, hidden: bool = False, deprecated: bool | str = False)
A custom command that can be used to mark options as deprecated.
References
Adapted from https://stackoverflow.com/a/50402799/13775459
- make_parser(ctx)
Hook ‘make_parser’ and during processing check the name used to invoke the option to see if it is preferred
- class flexmeasures.cli.utils.JSONOrFile
- convert(value, param, ctx)
Converts the input value to a Python dictionary.
- Args:
value (str): The input string from the command line. param (click.Parameter): The parameter instance. ctx (click.Context): The context instance.
- Returns:
dict: The parsed JSON data.
- Raises:
click.BadParameter: If the input is not a valid file path or JSON string.
- class flexmeasures.cli.utils.MsgStyle
Stores the text styles for the different events
Styles options are the attributes of the click.style which can be found [here](https://click.palletsprojects.com/en/8.1.x/api/#click.style).
- class flexmeasures.cli.utils.NestedDictParamType
Click parameter type that parses a JSON object or a Python-literal dict string.
Accepts both JSON double-quoted syntax (
{"key": "value"}) and Python-literal single-quoted syntax ({'key': 'value'}). Used for CLI options whose Marshmallow field type isfields.List(fields.Nested(...)).- convert(value, param, ctx)
Convert the value to the correct type. This is not called if the value is
None(the missing value).This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.
The
paramandctxarguments may beNonein certain situations, such as when converting prompt input.If the value cannot be converted, call
fail()with a descriptive message.- Parameters:
value – The value to convert.
param – The parameter that is using this type to convert its value. May be
None.ctx – The current context that arrived at this value. May be
None.