diff options
Diffstat (limited to 'dots_manager/env.py')
-rw-r--r-- | dots_manager/env.py | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/dots_manager/env.py b/dots_manager/env.py new file mode 100644 index 0000000..514624b --- /dev/null +++ b/dots_manager/env.py @@ -0,0 +1,56 @@ +import os +import json +import logging +from pathlib import Path +from dataclasses import dataclass +from typing import Dict, Any +from .config import Config +from .shell import run_shell_command +from .utils import merge_dicts +from .kawaii_logger import setup_logger + + +@dataclass(frozen=True) +class Environment: + platform: str + system_name: str + context: Dict[str, Any] + logger: logging.Logger + + +def initialize_environment(args) -> Environment: + logger = setup_logger(args.verbose) + scripts = args.source / Config.script_dir + platform = run_shell_command([str(scripts / "platform.sh")], logger) + if not platform: + raise ValueError("failed to determine platform... ") + os.environ["PLATFORM"] = platform + system_name = run_shell_command([str(scripts / "system_name.sh")], logger) + if not system_name: + raise ValueError("failed to determine system name... ") + context = load_context(platform, system_name, Config.contexts, logger) + return Environment(platform, system_name, context, logger) + + +def load_context(platform, system_name, context_file, logger): + try: + logger.info(f"reading context file: {context_file} ✧*:。゚✧") + with open(context_file) as f: + contexts = json.load(f) + + global_config = contexts.get("_global", {}) + platform_defaults = contexts.get(platform, {}).get("_default", {}) + defaults = merge_dicts(global_config, platform_defaults) + system_config = contexts.get(platform, {}).get(system_name, {}) + if not system_config: + logger.warning( + f"couldn’t find system-specific config for {platform}.{system_name} (ɐ•゚́•̀ɐ)" + ) + return { + "platform": platform, + "system_name": system_name, + **merge_dicts(defaults, system_config), + } + except (FileNotFoundError, json.JSONDecodeError) as e: + logger.error(f"error loading context: {e} ⋆ฺ°☁。⋆ฺ °★ °。") + return {} |