-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.py
164 lines (150 loc) · 4.57 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
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import atexit
import json
import logging
import os
import pprint
import completer
# according to the standard filesystem recommendation
CFGFILE = os.path.expanduser('~/.config/weight/weight.json')
# the global configuration dictionary
Config: dict[str,str] = {}
def getConfig(key: str, default=None):
"""
returns value from configuration
:param key: key
:param default: if not found, this will be returned and put into config
:return: the configuration value
"""
if key in Config:
return Config[key]
else:
if default is None:
return None
Config[key]=default
return default
def writeConfig():
"""
Writes configuration back at the end
"""
global Config
try:
bp = os.path.dirname(CFGFILE)
if not os.path.exists(bp):
os.mkdir(bp)
with open(CFGFILE, 'w') as outp:
json.dump(Config, outp, ensure_ascii=True, sort_keys=True, indent=2)
logging.debug('wrote config file %s' % CFGFILE)
except Exception as e:
logging.error('could not write %s due to %s' % (CFGFILE, e))
def listConfig(args: list[str]):
"""
prints out all configuration values
:param args: not used
"""
global Config
logging.debug('listening all configs')
maxKeyLength = 0
# determining the longest length of the keys
for key in Config:
if maxKeyLength < len(key):
maxKeyLength = len(key)
f = " {:>" + str(maxKeyLength) + "s} = {:}"
for key in Config:
print(f.format(key, Config[key]))
class DelConfigOpt(completer.ComplOption):
"""
A completer options for deleting values
"""
def prep(self, others: list[str], text: str) -> list[str]:
global Config
logging.debug("called with {} starting with {}".format(pprint.pformat(others),text))
fill=[]
for key in Config:
if key in others:
logging.debug(" already have {} in arguments".format(key))
continue
if key.startswith(text):
fill.append(key)
return fill
def exec(self, args: list[str]):
global Config
logging.debug("called")
for key in args:
logging.debug("deleting {}".format(key))
Config.pop(key, None)
class GetConfigOpt(DelConfigOpt):
"""
completer option for getting values
"""
def exec(self, args: list[str]):
global Config
maxKeyLength = 0
# determining the longest length of the keys
for key in Config:
if maxKeyLength < len(key):
maxKeyLength = len(key)
f = " {:>" + str(maxKeyLength) + "s} = {:s}"
for key in args:
print(f.format(key, Config[key]))
class SetConfigOpt(completer.ComplOption):
"""
Setting options, alternatively name value
"""
def prep(self, others: list[str], text: str) -> list[str]:
global Config
logging.debug("called with {} starting with {}".format(pprint.pformat(others),text))
fill=[]
if len(others)% 2 == 0:
for key in Config:
if key in others:
continue
if key.startswith(text):
fill.append(key)
else:
for key in Config:
val=Config[key]
if val in fill:
continue
if val.startswith(text):
fill.append(val)
return fill
def exec(self, args: list[str]):
"""
setting config value
:param args: list of pairs, name value
:return:
"""
global Config
for i in range(0,len(args),2):
key=args[i]
val=args[i+1]
Config[key]=val
def init_config():
# reading the config
global Config
logging.debug('reading config from %s' % CFGFILE)
try:
with open(CFGFILE) as inp:
Config = json.load(inp)
except:
logging.warning("couldn't read %s" % CFGFILE)
atexit.register(writeConfig)
# adding interactive editing of config values
cfg = completer.ComplOption('config')
# ---
cmdLst = completer.ComplOption('list', final=True)
cmdLst.exec = listConfig
cfg.add(cmdLst)
# ---
cmdSet = SetConfigOpt('set', final=True)
cfg.add(cmdSet)
# ---
cmdDel = DelConfigOpt('delete', final=True)
cfg.add(cmdDel)
# ---
cmdGet = GetConfigOpt('get', final=True)
cfg.add(cmdGet)
# ---
completer.rootCompleter.add(cfg)
Config['hello'] = 'world'
Config['yellow'] = 'submarine'