flexmeasures.cli.utils

Utils for FlexMeasures CLI

Functions

flexmeasures.cli.utils.abort(message: str)
flexmeasures.cli.utils.are_all_equal(paths: list[list[str]]) bool

Checks if all given entity paths represent the same path.

flexmeasures.cli.utils.done(message: str)
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: pytz.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"], ["Asset1", "Asset2"]]
>>> reduce_entity_paths([["Account1", "Asset", "Asset1"], ["Account1", "Asset", "Asset2"]])
[["Asset1"], ["Asset2"]]
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 Command object if it exists or returns None.

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 = 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

A Click parameter type that accepts either a JSON string or a file path to a JSON file.

It attempts to load the input as a file first. If that fails, it assumes the input is a JSON string and tries to parse it.

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.

name: str = 'json_or_file'

the descriptive name of this type

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).