-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig_reader.py
134 lines (96 loc) · 4.04 KB
/
config_reader.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import copy
import os
import json
from typing import Union
import yaml
from cerberus.validator import Validator, BareValidator
from types import SimpleNamespace
CFG_PATH = 'config.yaml'
def read_config() -> SimpleNamespace:
return json.loads(json.dumps(read_config_dict()), object_hook=lambda d: SimpleNamespace(**d))
def read_config_dict(no_templates=False) -> SimpleNamespace:
if not os.path.exists(CFG_PATH):
print(f"Error: Config file not found. (Path={CFG_PATH})")
return None
with open(CFG_PATH, 'r') as s:
try:
cfg: dict = yaml.safe_load(s)
if not no_templates:
cfg = apply_templates(cfg)
cfg = apply_vars(cfg)
return cfg
except Exception as ex:
print(f"Error: Cannot deserialize config file. Is your YAML valid? ({ex})")
return
def apply_templates(cfg: dict) -> dict:
if 'rules' in cfg:
for i, r in enumerate(cfg['rules']):
if 'template' in r and 'templates' in cfg and r['template'] in cfg['templates']:
r = r | cfg['templates'][r['template']]
cfg['rules'][i] = r
return cfg
def apply_vars(cfg: dict) -> dict:
if 'rules' in cfg:
for i, r in enumerate(cfg['rules']):
if 'vars' in r and len(r['vars']):
vs: dict = r['vars']
# Performs variable replacement using .format(**dict)
# 'regex' and 'selector' have the same configuration structure so do both in the same way
# Handles these being either lists or strings
for key in ['regex', 'selector']:
if key in r:
if isinstance(r[key], list):
r[key] = [st.format(**vs) for st in r[key]]
elif isinstance(r[key], str):
r[key] = r[key].format(**vs)
# Replace other vars for which it is only possible that they are strings
for key in ['url', 'link', 'referer']:
if key in r and isinstance(r[key], str):
r[key] = r[key].format(**vs)
cfg['rules'][i] = r
return cfg
def validate_config(cfg: dict) -> bool:
cfg = apply_templates(cfg)
with open('pricekeeper-schema.json', 'r') as sch:
schema = json.load(sch)
validator: BareValidator = Validator(schema)
is_valid = validator.validate(cfg)
if not is_valid:
raise ConfigValidationException(list(f"{e}: {str(validator.errors[e])}" for e in validator.errors))
return is_valid
class ConfigValidationException(Exception):
"""Raised when the configuration dictionary did not validate."""
def __init__(self, errors: list[str]) -> None:
self.errors = errors
super().__init__(errors[0])
pass
def write_config_dict(newCfg: dict) -> bool:
valCfg = copy.deepcopy(newCfg)
validate_config(valCfg)
try:
with open(CFG_PATH, 'w') as s:
s.write(yaml.dump(newCfg))
except:
return False
return True
def yaml_to_dict(yml: str) -> dict:
return yaml.safe_load(yml)
def get_yaml_rules() -> str:
return _get_yaml_section('rules')
def get_yaml_templates() -> str:
return _get_yaml_section('templates')
def _get_yaml_section(section: str) -> str:
if not os.path.exists(CFG_PATH):
print(f"Error: Config file not found. (Path={CFG_PATH})")
return None
with open(CFG_PATH, 'r') as s:
try:
yml = yaml.safe_load(s)
if section in yml:
return yaml.dump(yml[section])
return ''
except Exception as ex:
print(f"Error: Cannot deserialize config file. Is your YAML valid? ({ex})")
return '# ERROR - CHECK LOGS'
def merge_objects(s1: SimpleNamespace, s2: SimpleNamespace) -> SimpleNamespace:
return SimpleNamespace(**s1.__dict__, **s2.__dict__)