-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcfgman.py
58 lines (50 loc) · 1.62 KB
/
cfgman.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import contextlib
import logging
from pathlib import Path
from types import TracebackType
from typing import Any
import json
logger = logging.getLogger("hierpcb")
class ConfigMan(contextlib.AbstractContextManager):
def __init__(self, path: Path):
self.path = path
def __enter__(self) -> "ConfigMan":
try:
with self.path.open("r") as fp:
self.config = json.load(fp)
except FileNotFoundError:
logger.warning(f"Config file {self.path} not found. Creating new one.")
self.config = {}
return self
def __exit__(self, *args):
with self.path.open("w") as fp:
json.dump(self.config, fp, indent=2)
return super().__exit__(*args)
def get(self, *key: str, default=None):
node = self.config
for k in key:
node = node.get(k)
if node is None:
return default
return node
def clear(self, *key: str):
node = self.config
for k in key[:-1]:
node = node.get(k)
if node is None:
return
node.pop(key[-1], None)
def set(self, *key: str, value, create_missing=True):
node = self.config
terminal = key[-1]
prefix = []
for k in key[:-1]:
prefix.append(k)
node_next = node.get(k)
if node_next is None:
if create_missing:
node[k] = node_next = {}
else:
raise KeyError(f"Key {'.'.join(prefix)} not found in config.")
node = node_next
node[terminal] = value