Source code for tools.envvar
"""Helper functions to interface with environment variables."""
from __future__ import annotations
import typing
import os
@typing.overload
def get_environment_variable(env_var_name: str, is_bool: typing.Literal[True]) -> bool:
...
@typing.overload
def get_environment_variable(env_var_name: str, is_bool: typing.Literal[False]) -> str:
...
[docs]
def get_environment_variable(
env_var_name: str, is_bool: bool = False
) -> typing.Union[bool, str]:
"""Get the value of an environment variable.
Args:
env_var_name: Name of the environment variable to load
is_bool: whether the environment variable is assumed to be a boolean variable
(either ``false`` or ``true``). In this case, a boolean variable
is returned.
Raise:
AssertionError: The environment variable does not exist
AssertionError: ``is_bool`` but the environment is neither ``true``
nor ``false``
"""
assert env_var_name in os.environ, (
str(env_var_name) + " is not recognised as an environment variable"
)
env_var = os.environ[env_var_name]
if is_bool:
assert env_var == "false" or env_var == "true"
return env_var == "true"
else:
return env_var
[docs]
def get_repo_path() -> str:
"""Get the path to root of the repository."""
return get_environment_variable(env_var_name="XDIGI2CSV_REPO")
[docs]
def set_environment_variable(env_var_name: str, value: str | bool):
"""Create and environment variable.
Args:
env_var_name: name of the environment variable
value: value of the environment variable. If boolean, the variable is set
to ``true`` or ``false``
"""
assert "env_var_name" not in os.environ, (
"the `" + env_var_name + "` env. var. is already set."
)
if isinstance(value, bool):
os.environ[env_var_name] = "true" if value else "false"
else:
assert isinstance(value, str)
os.environ[env_var_name] = value
@typing.overload
def resolve_wildcards(strings: str) -> str:
...
@typing.overload
def resolve_wildcards(strings: typing.List[str]) -> typing.List[str]:
...
[docs]
def resolve_wildcards(strings: str | typing.List[str]) -> str | typing.List[str]:
"""Replace wildcards or placeholders in strings by the corresponding
environment variables.
Args:
strings: a string or list of strings
Returns:
string or list of strings with any placeholders replaced by the corresponding
environment variable.
Notes:
An error is raised of not all the placeholders are replaced
"""
if isinstance(strings, str):
return strings.format(**os.environ)
else:
return [resolve_wildcards(string) for string in strings]