Files
mytoolkit/bin/config.py
T
Zhengshou Lai c1df4098b3 refactor: rename package from mytoolkit to bin
- Move all source files from mytoolkit/ to bin/
- Update entry point and build config in pyproject.toml
- Add pillow and pypdf dependencies
- Update README and .gitignore paths
- Remove unused subprocess import in pdf.py
- Clean up duplicate imports in pdf merge command
2026-04-26 09:56:29 +08:00

56 lines
1.5 KiB
Python

"""Configuration management for bin."""
import json
from pathlib import Path
class Config:
"""Simple config manager for environment variables."""
def __init__(self):
self._config_path = Path(__file__).parent / "config.json"
self._data = self._load()
def _load(self) -> dict:
if self._config_path.exists():
with open(self._config_path) as f:
return json.load(f)
return {"vars": {}}
def save(self):
"""Save config to file."""
with open(self._config_path, "w") 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()