-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.py
56 lines (49 loc) · 1.65 KB
/
config.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
#!/usr/bin/env python3
from json import load
from typing import Optional
from re import compile as regexp, Match
from sys import argv
REGEX_LOOKUP = regexp(r'\$\{([^}]*)\}')
REGEX_LOOKUPCMD = regexp(r'\|(\w+)\(([^)]*)\)')
with open('./settings.json', 'r') as fh:
config = load(fh)
def get_value(key: str, default: Optional[str] = None) -> Optional[str]:
value = config
if key.startswith('#'):
return ''
for part in key.split('.'):
if match := REGEX_LOOKUPCMD.match(part):
command, args = match.groups()
if command in ('j', 'join'):
value = str.join(' ', [
process_value(value[k]) for k in args.split(',')
])
elif isinstance(value, list):
index = int(part)
if index >= len(value):
return default
value = value[index]
elif part not in value:
return default
elif isinstance(value, dict):
value = value[part]
else:
print(value, part)
raise ValueError('oopsie')
return value
def replace_value(match: Match) -> str:
lookup, *pipeline = match.groups()[0].split(':')
if lookup.startswith('#'):
return ''
value = get_value(lookup) or ''
for sub in pipeline:
if sub[0] == 's':
a, b = sub[2:].split(sub[1])
value = value.replace(a, b)
elif sub[0] == 'u':
value = value.upper()
return process_value(value)
def process_value(value: str) -> str:
return REGEX_LOOKUP.sub(replace_value, value)
def lookup(key: str) -> str:
return process_value(get_value(key) or '')