Skip to content

ConfigurationManager

Configuration management for ezpl.

Overview

The ConfigurationManager class manages configuration from multiple sources (environment variables, config file, defaults) with a clear priority order.

Class Reference

ConfigurationManager

ConfigurationManager(config_file: Path | None = None)

Centralized configuration manager for Ezpl.

This class handles all configuration operations including loading, saving, and merging configuration from multiple sources.

Initialize the configuration manager.

PARAMETER DESCRIPTION
config_file

Optional path to configuration file. Defaults to ~/.ezpl/config.json

TYPE: Path | None DEFAULT: None

Source code in src/ezpl/config/manager.py
def __init__(self, config_file: Path | None = None):
    """
    Initialize the configuration manager.

    Args:
        config_file: Optional path to configuration file.
                    Defaults to ~/.ezpl/config.json
    """
    self._config_file = config_file or DefaultConfiguration.CONFIG_FILE
    self._config: dict[str, Any] = {}
    self._load_configuration()

Attributes

config_file property

config_file: Path

Return the path to the configuration file.

Functions

get

get(key: str, default: Any = None) -> Any

Get a configuration value.

PARAMETER DESCRIPTION
key

Configuration key

TYPE: str

default

Default value if key not found

TYPE: Any DEFAULT: None

RETURNS DESCRIPTION
Any

Configuration value or default

Source code in src/ezpl/config/manager.py
def get(self, key: str, default: Any = None) -> Any:
    """
    Get a configuration value.

    Args:
        key: Configuration key
        default: Default value if key not found

    Returns:
        Configuration value or default
    """
    return self._config.get(key, default)

has_key

has_key(key: str) -> bool

Check if a configuration key is explicitly set (not just a default).

PARAMETER DESCRIPTION
key

Configuration key to check

TYPE: str

RETURNS DESCRIPTION
bool

True if the key is explicitly set in config or environment, False otherwise

Source code in src/ezpl/config/manager.py
def has_key(self, key: str) -> bool:
    """
    Check if a configuration key is explicitly set (not just a default).

    Args:
        key: Configuration key to check

    Returns:
        True if the key is explicitly set in config or environment, False otherwise
    """
    # Check if key exists in config (from file or explicitly set)
    if key in self._config:
        return True
    # Check if corresponding environment variable exists
    env_key = f"EZPL_{key.replace('-', '_').upper()}"
    return env_key in os.environ

get_log_level

get_log_level() -> str

Get the current log level.

Source code in src/ezpl/config/manager.py
def get_log_level(self) -> str:
    """Get the current log level."""
    return cast(str, self.get("log-level", DefaultConfiguration.LOG_LEVEL))

get_log_file

get_log_file() -> Path

Get the current log file path.

Source code in src/ezpl/config/manager.py
def get_log_file(self) -> Path:
    """Get the current log file path."""
    log_file = self.get("log-file", DefaultConfiguration.LOG_FILE)
    log_dir = self.get("log-dir", DefaultConfiguration.LOG_DIR)

    # Convert to Path if string
    log_file_path = Path(log_file) if isinstance(log_file, str) else log_file
    log_dir_path = Path(log_dir) if isinstance(log_dir, str) else log_dir

    # If log_file is relative, make it relative to log_dir
    if not log_file_path.is_absolute():
        return log_dir_path / log_file_path
    return log_file_path

get_printer_level

get_printer_level() -> str

Get the current printer level.

Source code in src/ezpl/config/manager.py
def get_printer_level(self) -> str:
    """Get the current printer level."""
    return cast(str, self.get("printer-level", DefaultConfiguration.PRINTER_LEVEL))

get_file_logger_level

get_file_logger_level() -> str

Get the current file logger level.

Source code in src/ezpl/config/manager.py
def get_file_logger_level(self) -> str:
    """Get the current file logger level."""
    return cast(
        str, self.get("file-logger-level", DefaultConfiguration.FILE_LOGGER_LEVEL)
    )

get_indent_step

get_indent_step() -> int

Get the current indent step.

Source code in src/ezpl/config/manager.py
def get_indent_step(self) -> int:
    """Get the current indent step."""
    return cast(int, self.get("indent-step", DefaultConfiguration.INDENT_STEP))

get_indent_symbol

get_indent_symbol() -> str

Get the current indent symbol.

Source code in src/ezpl/config/manager.py
def get_indent_symbol(self) -> str:
    """Get the current indent symbol."""
    return cast(str, self.get("indent-symbol", DefaultConfiguration.INDENT_SYMBOL))

get_base_indent_symbol

get_base_indent_symbol() -> str

Get the current base indent symbol.

Source code in src/ezpl/config/manager.py
def get_base_indent_symbol(self) -> str:
    """Get the current base indent symbol."""
    return cast(
        str, self.get("base-indent-symbol", DefaultConfiguration.BASE_INDENT_SYMBOL)
    )

get_log_format

get_log_format() -> str

Get the current log format.

Source code in src/ezpl/config/manager.py
def get_log_format(self) -> str:
    """Get the current log format."""
    return cast(str, self.get("log-format", DefaultConfiguration.LOG_FORMAT))

get_log_rotation

get_log_rotation() -> str | None

Get the current log rotation setting.

Source code in src/ezpl/config/manager.py
def get_log_rotation(self) -> str | None:
    """Get the current log rotation setting."""
    return cast(
        str | None, self.get("log-rotation", DefaultConfiguration.LOG_ROTATION)
    )

get_log_retention

get_log_retention() -> str | None

Get the current log retention setting.

Source code in src/ezpl/config/manager.py
def get_log_retention(self) -> str | None:
    """Get the current log retention setting."""
    return cast(
        str | None, self.get("log-retention", DefaultConfiguration.LOG_RETENTION)
    )

get_log_compression

get_log_compression() -> str | None

Get the current log compression setting.

Source code in src/ezpl/config/manager.py
def get_log_compression(self) -> str | None:
    """Get the current log compression setting."""
    return cast(
        str | None,
        self.get("log-compression", DefaultConfiguration.LOG_COMPRESSION),
    )

get_all

get_all() -> dict[str, Any]

Get all configuration values.

RETURNS DESCRIPTION
dict[str, Any]

Dictionary containing all configuration values

Source code in src/ezpl/config/manager.py
def get_all(self) -> dict[str, Any]:
    """
    Get all configuration values.

    Returns:
        Dictionary containing all configuration values
    """
    return self._config.copy()

set

set(key: str, value: Any) -> None

Set a configuration value.

PARAMETER DESCRIPTION
key

Configuration key

TYPE: str

value

Configuration value

TYPE: Any

Source code in src/ezpl/config/manager.py
def set(self, key: str, value: Any) -> None:
    """
    Set a configuration value.

    Args:
        key: Configuration key
        value: Configuration value
    """
    self._config[key] = value

update

update(config_dict: dict[str, Any]) -> None

Update configuration with new values.

PARAMETER DESCRIPTION
config_dict

Dictionary of configuration values to update

TYPE: dict[str, Any]

Source code in src/ezpl/config/manager.py
def update(self, config_dict: dict[str, Any]) -> None:
    """
    Update configuration with new values.

    Args:
        config_dict: Dictionary of configuration values to update
    """
    self._config.update(config_dict)

save

save() -> None

Save current configuration to file.

RAISES DESCRIPTION
FileOperationError

If unable to write to configuration file

Source code in src/ezpl/config/manager.py
def save(self) -> None:
    """
    Save current configuration to file.

    Raises:
        FileOperationError: If unable to write to configuration file
    """
    try:
        # Ensure config directory exists
        self._config_file.parent.mkdir(parents=True, exist_ok=True)

        # Save configuration
        with open(self._config_file, "w", encoding="utf-8") as f:
            json.dump(self._config, f, indent=4, ensure_ascii=False)
    except OSError as e:
        raise FileOperationError(
            f"Could not save configuration to {self._config_file}: {e}",
            str(self._config_file),
            "save",
        ) from e

reset_to_defaults

reset_to_defaults() -> None

Reset configuration to default values.

Source code in src/ezpl/config/manager.py
def reset_to_defaults(self) -> None:
    """Reset configuration to default values."""
    self._config = DefaultConfiguration.get_all_defaults().copy()

reload

reload() -> None

Reload configuration from file and environment variables.

This method reloads the configuration, useful when environment variables or the config file have changed after initialization.

Source code in src/ezpl/config/manager.py
def reload(self) -> None:
    """
    Reload configuration from file and environment variables.

    This method reloads the configuration, useful when environment
    variables or the config file have changed after initialization.
    """
    self._load_configuration()

export_to_script

export_to_script(output_file: str | Path, platform: str | None = None) -> None

Export configuration as environment variables script.

PARAMETER DESCRIPTION
output_file

Path to output script file

TYPE: str | Path

platform

Target platform ('windows', 'unix', or None for auto-detect)

TYPE: str | None DEFAULT: None

RAISES DESCRIPTION
FileOperationError

If unable to write to output file

Source code in src/ezpl/config/manager.py
def export_to_script(
    self, output_file: str | Path, platform: str | None = None
) -> None:
    """
    Export configuration as environment variables script.

    Args:
        output_file: Path to output script file
        platform: Target platform ('windows', 'unix', or None for auto-detect)

    Raises:
        FileOperationError: If unable to write to output file
    """
    if platform is None:
        import sys

        platform = "windows" if sys.platform == "win32" else "unix"

    output_path = Path(output_file)

    try:
        with open(output_path, "w", encoding="utf-8") as f:
            if platform == "windows":
                # Generate Batch script for Windows
                for env_var, config_key in self.ENV_MAPPINGS.items():
                    value = self._config.get(config_key)
                    if value is None:
                        continue
                    f.write(f"set {env_var}={value}\n")
            else:
                # Generate Bash script for Unix/Linux/macOS
                f.write("#!/bin/bash\n")
                for env_var, config_key in self.ENV_MAPPINGS.items():
                    value = self._config.get(config_key)
                    if value is None:
                        continue
                    f.write(f"export {env_var}={shlex.quote(str(value))}\n")
    except OSError as e:
        raise FileOperationError(
            f"Could not write to {output_path}: {e}",
            str(output_path),
            "export",
        ) from e