Files
mytoolkit/mycli/config.py
T

78 lines
2.2 KiB
Python

"""Configuration management for mycli."""
import json
import os
from pathlib import Path
from typing import Any
class Config:
"""Configuration manager."""
def __init__(self):
self._data: dict = {}
self._config_path = Path(__file__).parent / "config.json"
self._load()
def _load(self):
"""Load configuration from JSON file."""
if self._config_path.exists():
with open(self._config_path) as f:
self._data = json.load(f)
else:
self._data = {}
def get(self, key: str, default: Any = None) -> Any:
"""Get configuration value by dot notation key.
Examples:
config.get("paths.research")
config.get("ssh_hosts.tianhe.port")
"""
keys = key.split(".")
value = self._data
for k in keys:
if isinstance(value, dict) and k in value:
value = value[k]
else:
return default
return value
def get_path(self, name: str) -> Path | None:
"""Get a path and expand ~ to home directory."""
path_str = self.get(f"paths.{name}")
if path_str:
return Path(path_str).expanduser()
return None
def get_all_paths(self) -> dict[str, Path]:
"""Get all paths as Path objects."""
paths = self.get("paths", {})
return {name: Path(path).expanduser() for name, path in paths.items()}
def get_ssh_host(self, name: str) -> dict | None:
"""Get SSH host configuration."""
return self.get(f"ssh_hosts.{name}")
def get_git_proxy(self, name: str) -> str | None:
"""Get Git proxy URL."""
return self.get(f"git_proxies.{name}")
def get_all_git_proxies(self) -> dict[str, str]:
"""Get all Git proxy configurations."""
return self.get("git_proxies", {})
def edit(self):
"""Open config file in default editor."""
editor = os.environ.get("EDITOR", "vim")
os.system(f"{editor} {self._config_path}")
def show(self):
"""Display configuration."""
import json
print(json.dumps(self._data, indent=2, ensure_ascii=False))
# Global config instance
config = Config()