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
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_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
"""
# Get the appropriate database URL key based on the environment
key = "DEV_DATABASE_URL" if env.is_dev else "PROD_DATABASE_URL"
url = self.get(key, default="")
if not url:
# If no URL is found, raise an error.
# We no longer provide a default/mock URL here.
error_msg = f"No database URL found for the {env.value.upper()} environment."
raise ConfigurationError(error_msg)
return 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
"""
# Get the appropriate bot token key based on the environment
key = "DEV_BOT_TOKEN" if env.is_dev else "PROD_BOT_TOKEN"
token = self.get(key, default="")
if not token:
# If no token is found, raise an error.
error_msg = f"No bot token found for the {env.value.upper()} environment."
raise ConfigurationError(error_msg)
return token
EnvironmentManager()
¶
Core manager for application environment.
This class handles all environment-related operations including setting the environment mode and managing configuration.
Initialize the environment manager if not already initialized.
Methods:
Name | Description |
---|---|
__new__ | Create or return the singleton instance. |
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¶
__new__(*args: Any, **kwargs: Any) -> EnvironmentManager
¶
Create or return the singleton instance.
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)