Initial upload: TermDiagram v0.1.0
This commit is contained in:
49
src/termdiagram/utils/config.py
Normal file
49
src/termdiagram/utils/config.py
Normal file
@@ -0,0 +1,49 @@
|
||||
from typing import Dict, Any, Optional
|
||||
from pathlib import Path
|
||||
import json
|
||||
import yaml
|
||||
|
||||
|
||||
class Config:
|
||||
def __init__(self, config_path: Optional[str] = None):
|
||||
self.config: Dict[str, Any] = {
|
||||
"output_format": "ascii",
|
||||
"extensions": [],
|
||||
"exclude": [],
|
||||
"max_methods": 5,
|
||||
"show_imports": True,
|
||||
}
|
||||
|
||||
if config_path:
|
||||
self.load(config_path)
|
||||
|
||||
def load(self, config_path: str):
|
||||
path = Path(config_path)
|
||||
|
||||
if path.suffix == ".json":
|
||||
self._load_json(path)
|
||||
elif path.suffix in (".yaml", ".yml"):
|
||||
self._load_yaml(path)
|
||||
|
||||
def _load_json(self, path: Path):
|
||||
try:
|
||||
with open(path, "r") as f:
|
||||
data = json.load(f)
|
||||
self.config.update(data)
|
||||
except (IOError, json.JSONDecodeError):
|
||||
pass
|
||||
|
||||
def _load_yaml(self, path: Path):
|
||||
try:
|
||||
with open(path, "r") as f:
|
||||
data = yaml.safe_load(f)
|
||||
if data:
|
||||
self.config.update(data)
|
||||
except (IOError, yaml.YAMLError):
|
||||
pass
|
||||
|
||||
def get(self, key: str, default: Any = None) -> Any:
|
||||
return self.config.get(key, default)
|
||||
|
||||
def set(self, key: str, value: Any):
|
||||
self.config[key] = value
|
||||
Reference in New Issue
Block a user