tux.utils.env
¶
Environment management utility for Tux.
This module provides centralized environment configuration management, following 12-factor app methodology for configuration.
Classes:
Name | Description |
---|---|
EnvError | Base exception for environment-related errors. |
ConfigurationError | Exception raised for configuration issues. |
Environment | Environment types supported by the application. |
Config | Configuration manager responsible for handling environment variables. |
EnvironmentManager | Core manager for application environment. |
Functions:
Name | Description |
---|---|
is_dev_mode | Check if application is running in development mode. |
is_prod_mode | Check if application is running in production mode. |
get_current_env | Get current environment name. |
set_env_mode | Set environment mode. |
get_database_url | Get database URL for current environment. |
get_bot_token | Get bot token for current environment. |
get_config | Get configuration manager. |
configure_environment | Configure the global application environment mode. |
Classes¶
Environment
¶
Config(dotenv_path: Path | None = None, load_env: bool = True)
¶
Configuration manager responsible for handling environment variables.
Initialize configuration manager.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dotenv_path | Optional[Path] | Path to .env file | None |
load_env | bool | Whether to load environment from .env file | True |
Methods:
Name | Description |
---|---|
get | Get environment variable with type conversion. |
set | Set environment variable. |
get_database_url | Get database URL for specified environment. |
get_bot_token | Get bot token for specified environment. |
Source code in tux/utils/env.py
def __init__(self, dotenv_path: Path | None = None, load_env: bool = True):
"""
Initialize configuration manager.
Parameters
----------
dotenv_path : Optional[Path]
Path to .env file
load_env : bool
Whether to load environment from .env file
"""
# Core paths
self.workspace_root = Path(__file__).parent.parent.parent
if self.workspace_root.name == "tux":
# If we're in the tux package, this is the workspace root
pass
elif self.workspace_root.parent.name == "tux":
# If we're in tests/tux, go up one more level
self.workspace_root = self.workspace_root.parent
self.dotenv_path = dotenv_path or self.workspace_root / ".env"
# Load environment variables
if load_env and self.dotenv_path.exists():
load_dotenv(dotenv_path=self.dotenv_path, verbose=False)
Functions¶
get(key: str, default: T | None = None, required: bool = False) -> T | None
¶
Get environment variable with type conversion.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key | str | Environment variable name | required |
default | Optional[T] | Default value if not found | None |
required | bool | Whether this variable is required | False |
Returns:
Type | Description |
---|---|
Optional[T] | The value of the environment variable |
Raises:
Type | Description |
---|---|
ConfigurationError | If variable is required but not found |
Source code in tux/utils/env.py
def get(self, key: str, default: T | None = None, required: bool = False) -> T | None:
"""
Get environment variable with type conversion.
Parameters
----------
key : str
Environment variable name
default : Optional[T]
Default value if not found
required : bool
Whether this variable is required
Returns
-------
Optional[T]
The value of the environment variable
Raises
------
ConfigurationError
If variable is required but not found
"""
value = os.environ.get(key)
if value is None:
if required:
error_msg = f"Required environment variable {key} is not set"
raise ConfigurationError(error_msg)
return default
# If default is provided, attempt to cast to the same type
if default is not None:
try:
if isinstance(default, bool):
return value.lower() in ("true", "yes", "1", "y") # type: ignore
return type(default)(value) # type: ignore
except ValueError as e:
if required:
error_msg = f"Environment variable {key} is not a valid {type(default).__name__}"
raise ConfigurationError(error_msg) from e
return default
return value # type: ignore
set(key: str, value: Any, persist: bool = False) -> None
¶
Set environment variable.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key | str | Environment variable name | required |
value | Any | Value to set | required |
persist | bool | Whether to persist to .env file | False |
Source code in tux/utils/env.py
def set(self, key: str, value: Any, persist: bool = False) -> None:
"""
Set environment variable.
Parameters
----------
key : str
Environment variable name
value : Any
Value to set
persist : bool
Whether to persist to .env file
"""
os.environ[key] = str(value)
if persist and self.dotenv_path.exists():
set_key(self.dotenv_path, key, str(value))
_get_env_specific_value(env: Environment, dev_key: str, prod_key: str, value_name: str) -> str
¶
Get environment-specific configuration value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
env | Environment | The environment to get value for | required |
dev_key | str | Environment variable key for development | required |
prod_key | str | Environment variable key for production | required |
value_name | str | Human-readable name for error messages | required |
Returns:
Type | Description |
---|---|
str | Configuration value |
Raises:
Type | Description |
---|---|
ConfigurationError | If value is not configured for environment |
Source code in tux/utils/env.py
def _get_env_specific_value(self, env: Environment, dev_key: str, prod_key: str, value_name: str) -> str:
"""
Get environment-specific configuration value.
Parameters
----------
env : Environment
The environment to get value for
dev_key : str
Environment variable key for development
prod_key : str
Environment variable key for production
value_name : str
Human-readable name for error messages
Returns
-------
str
Configuration value
Raises
------
ConfigurationError
If value is not configured for environment
"""
key = dev_key if env.is_dev else prod_key
value = self.get(key) # Don't provide a default value
if value is None:
error_msg = f"No {value_name} found for the {env.value.upper()} environment."
raise ConfigurationError(error_msg)
return value
get_database_url(env: Environment) -> str
¶
Get database URL for specified environment.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
env | Environment | The environment to get URL for | required |
Returns:
Type | Description |
---|---|
str | Database URL |
Raises:
Type | Description |
---|---|
ConfigurationError | If database URL is not configured for environment |
Source code in tux/utils/env.py
def get_database_url(self, env: Environment) -> str:
"""
Get database URL for specified environment.
Parameters
----------
env : Environment
The environment to get URL for
Returns
-------
str
Database URL
Raises
------
ConfigurationError
If database URL is not configured for environment
"""
return self._get_env_specific_value(env, "DEV_DATABASE_URL", "PROD_DATABASE_URL", "database URL")
get_bot_token(env: Environment) -> str
¶
Get bot token for specified environment.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
env | Environment | The environment to get token for | required |
Returns:
Type | Description |
---|---|
str | Bot token |
Raises:
Type | Description |
---|---|
ConfigurationError | If bot token is not configured for environment |
Source code in tux/utils/env.py
def get_bot_token(self, env: Environment) -> str:
"""
Get bot token for specified environment.
Parameters
----------
env : Environment
The environment to get token for
Returns
-------
str
Bot token
Raises
------
ConfigurationError
If bot token is not configured for environment
"""
return self._get_env_specific_value(env, "DEV_BOT_TOKEN", "PROD_BOT_TOKEN", "bot token")
EnvironmentManager()
¶
Core manager for application environment.
This class handles all environment-related operations including setting the environment mode and managing configuration.
Initialize environment manager.
Methods:
Name | Description |
---|---|
reset_for_testing | Reset the singleton instance for testing purposes. |
__new__ | Ensure singleton pattern. |
configure | Configure the environment mode. |
Attributes:
Name | Type | Description |
---|---|---|
environment | Environment | Get the current environment. |
config | Config | Get the configuration manager. |
Source code in tux/utils/env.py
Attributes¶
environment: Environment
property
writable
¶
Get the current environment.
config: Config
property
¶
Get the configuration manager.
Functions¶
reset_for_testing() -> None
classmethod
¶
__new__(*args: Any, **kwargs: Any) -> EnvironmentManager
¶
configure(environment: Environment) -> None
¶
Configure the environment mode.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
environment | Environment | The environment mode to set (DEVELOPMENT or PRODUCTION) | required |
Functions¶
is_dev_mode() -> bool
¶
is_prod_mode() -> bool
¶
get_current_env() -> str
¶
set_env_mode(dev_mode: bool) -> None
¶
Set environment mode.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dev_mode | bool | True for development, False for production | required |
get_database_url() -> str
¶
get_bot_token() -> str
¶
get_config() -> Config
¶
configure_environment(dev_mode: bool) -> None
¶
Configure the global application environment mode.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dev_mode | bool | True to set development mode, False to set production mode. | required |
Source code in tux/utils/env.py
def configure_environment(dev_mode: bool) -> None:
"""
Configure the global application environment mode.
Parameters
----------
dev_mode : bool
True to set development mode, False to set production mode.
"""
env_mode = Environment.DEVELOPMENT if dev_mode else Environment.PRODUCTION
_env_manager.configure(env_mode)