Files
mytoolkit/bin/config.py
T

69 lines
2.1 KiB
Python

"""Configuration management for bin."""
import json
import os
from pathlib import Path
_MYTOOLKIT_HOME = Path(os.environ.get("MYTOOLKIT_HOME", Path.home() / ".mytoolkit"))
CONFIG_PATH = _MYTOOLKIT_HOME / "env.json"
_LEGACY_PATH = Path(__file__).parent / "config.json"
class Config:
"""Simple config manager for environment variables."""
def __init__(self):
self._config_path = CONFIG_PATH
self._migrate_legacy()
self._data = self._load()
def _migrate_legacy(self) -> None:
"""One-shot move of legacy bin/config.json into the user config dir."""
if _LEGACY_PATH.exists() and not self._config_path.exists():
self._config_path.parent.mkdir(parents=True, exist_ok=True)
_LEGACY_PATH.rename(self._config_path)
def _load(self) -> dict:
if self._config_path.exists():
with open(self._config_path, encoding="utf-8") as f:
return json.load(f)
return {"vars": {}}
def save(self):
"""Save config to file."""
self._config_path.parent.mkdir(parents=True, exist_ok=True)
with open(self._config_path, "w", encoding="utf-8") as f:
json.dump(self._data, f, indent=2, ensure_ascii=False)
f.write("\n")
def get(self, name: str) -> str | None:
"""Get var by name."""
return self._data.get("vars", {}).get(name)
def get_all(self) -> dict[str, str]:
"""Get all vars."""
return self._data.get("vars", {}).copy()
def set(self, name: str, value: str):
"""Set a var."""
if "vars" not in self._data:
self._data["vars"] = {}
self._data["vars"][name] = value
self.save()
def remove(self, name: str) -> bool:
"""Remove a var. Returns True if existed."""
if name in self._data.get("vars", {}):
del self._data["vars"][name]
self.save()
return True
return False
def export(self) -> dict[str, str]:
"""Get all vars with env-compatible names."""
return {f"MYCLI_{k.upper()}": v for k, v in self.get_all().items()}
# Global instance
config = Config()