Menu

[8f66b6]: / tools / Config.py  Maximize  Restore  History

Download this file

259 lines (225 with data), 9.9 kB

  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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# -*- coding: utf-8 -*-
"""
Copyright (C) 2011 Oliver Tengler
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import re
import types
import unittest
from typing import TypeVar, Any, Dict, Callable, Tuple, Iterator, cast
from tools.FileTools import fopen
T = TypeVar('T')
def identity (a: T) -> T:
return a
def boolParse (value: Any) -> bool:
if type(value) == bool:
return cast(bool, value)
if type(value) == str:
value = value.lower()
if value == "true" or value == "1" or value == "yes":
return True
if value == "false" or value == "0" or value == "no":
return False
if type(value) == int:
return bool(value)
raise RuntimeError("Unknown boolean value '" + value + "'")
def boolPersist (value: Any) -> str:
if type(value) == bool:
return str(value)
if type(value) == str:
value = value.lower()
if value == "true" or value == "1" or value == "yes":
return "True"
if value == "false" or value == "0" or value == "no":
return "False"
if type (value) == int:
if value:
return "True"
return "False"
raise RuntimeError("Cannot interpret '" + str(value) + "' as bool")
def plainTypeMapper(t: Any) -> Tuple[Callable, Callable, Callable]:
if bool == t:
return (boolParse, lambda: None, boolPersist)
if int == t:
return (int, lambda: None, str)
return (identity, lambda: None, str)
# A object which holds configuration data. The data is accessed like a property. It can contain objects of itself
# which allows to build deeper stacked configs.
# E.g.:
# c = Config()
# c.sub = Config()
# c.sub.a = "Text"
class Config:
def __init__ (self, name: str="", dataMap: Dict[str,Any]=None, configLines:Iterator[str]=None, typeInfoFunc: Callable=None) -> None:
self.__data = dataMap or {}
self.__typeMapper: Dict[str,Tuple[Callable,Callable,Callable]] = {}
if typeInfoFunc:
typeInfoFunc(self)
if name:
self.loadFile(name)
elif configLines:
self.parseLines(configLines)
def setPlainType(self, attr: str, attrType: Any) -> None:
self.__typeMapper[attr.lower()] = plainTypeMapper(attrType)
def setType (self, attr: str, typeFuncs: Tuple[Callable, Callable, Callable]) -> None:
self.__typeMapper[attr.lower()] = typeFuncs
def __typeParse (self, attr: str) -> Callable:
if attr in self.__typeMapper:
return self.__typeMapper[attr][0]
return lambda a: a
def __typeNotFound (self, attr: str) -> Callable:
if attr in self.__typeMapper:
return self.__typeMapper[attr][1]
return lambda:None
def __typePersist (self, attr: str) -> Callable:
if attr in self.__typeMapper:
return self.__typeMapper[attr][2]
return str
def __getattr__ (self, attr: str) -> Any:
attr = attr.lower()
if attr in self.__data:
return self.__typeParse(attr)(self.__data[attr])
result = self.__typeNotFound(attr)()
if result is not None:
if isinstance(result, Config):
self.__data[attr] = result
return result
raise AttributeError(attr + " does not exist in the configuration")
def __getitem__(self, attr: str) -> Any:
attr = attr.lower()
return self.__data[attr]
def __contains__(self, attr: str) -> bool:
return attr.lower() in self.__data
def __setattr__(self, attr: str, value: Any) -> None:
if attr.startswith("_Config__"):
super().__setattr__(attr, value)
return
attr = attr.lower()
if isinstance(value, Config):
self.__data[attr] = value
else:
v = self.__typeParse(attr)(value)
self.__data[attr] = v
def __iter__(self) -> Any:
return self.__data.__iter__()
def values(self) -> Any:
return self.__data.values()
def __repr__ (self) -> str:
return self.__dumpRec (self, 0)
def __dumpRec (self, config: 'Config', level: int) -> str:
s = ""
for k,v in config.__data.items(): # access of protected member pylint: disable=W0212
if s:
s += "\n"
s = s + " " *2*level + k
if type(v) is Config:
s += " {\n"
s = s + self.__dumpRec (v, level+1)
s = s + "\n" + " " *2*level + "}"
else:
s = s + " = " + config.__typePersist(k)(v) # access of protected member pylint: disable=W0212
return s
def remove (self, key: str) -> None:
key = key.lower()
if key in self.__data:
del self.__data[key]
def loadFile (self, name: str) -> None:
with fopen(name) as file:
self.parseLines ((line for line in file.readlines()))
def parseLines(self, lines: Iterator[str]) -> None:
if type(lines) is not types.GeneratorType:
raise TypeError("lines must be a generator type")
for line in lines:
line = line.strip()
try:
if not line or line.startswith("#"): # ignore empty lines and comments
continue
equalSign = line.find("=")
if equalSign != -1:
key = line[:equalSign]
value = line[equalSign+1:]
setattr(self, key.strip(), value.strip())
elif line.startswith("import"):
self.__handleImport(line)
elif line.startswith("}"):
return
elif line.endswith("{"):
groupname = line.split("{")[0].strip().lower()
if groupname in self.__data:
group = self.__data[groupname]
group.parseLines (lines)
else:
try:
group = getattr(self, groupname) # This allows to apply type information from __typeNotFound funcs
except AttributeError:
group = Config()
group.parseLines(lines)
setattr (self, groupname, group)
except:
print ("Do not understand line: " + line)
raise
def __handleImport (self, line: str) -> None:
# syntax: import file as groupname
# This imports the file into the group 'groupname'. If the group already exists it is merged
importTokens = re.match("import\\W+([\\w\\\\/\\.]+)\\W+as\\W+(\\w+)", line)
if importTokens:
groupname = importTokens.group(2).lower()
filename = importTokens.group(1)
try:
group = getattr(self, groupname) # This allows to apply type information from __typeNotFound funcs
except AttributeError:
group = Config()
try:
group.loadFile (filename)
setattr (self, groupname, group)
except IOError:
pass
else:
# syntax: import file
# This imports all properties of the file into the current config.
importTokens = re.match("import\\W+([\\w\\\\/\\.]+)", line)
if not importTokens:
raise RuntimeError("wrong import line")
try:
Config(importTokens.group(1), dataMap=self.__data)
except IOError:
pass
def typeDefaultBool (bDefault: bool) -> Tuple[Callable, Callable, Callable]:
return (boolParse, lambda: bDefault, boolPersist)
def typeDefaultInt (iDefault: int) -> Tuple[Callable, Callable, Callable]:
return (int, lambda: iDefault, str)
def typeDefaultString (strDefault: str) -> Tuple[Callable, Callable, Callable]:
return (identity, lambda: strDefault, str)
def typeDefaultConfig () -> Tuple[Callable, Callable, Callable]:
return (identity, lambda: Config(), identity) # Lambda may not be neccessary pylint: disable=W0108
class TestConfig(unittest.TestCase):
def test(self) -> None:
c = Config()
c.setPlainType ("b1", bool)
c.setType("b2", typeDefaultBool(True))
with self.assertRaises(AttributeError):
c.b1 # pylint: disable=W0104
self.assertEqual(c.b2, True)
c.b1 = False # pylint: disable=W0201
self.assertEqual(c.b1, False)
c.text = "Hallo" # pylint: disable=W0201
self.assertEqual(c.text, "Hallo")
c.setType("di", typeDefaultInt(42))
self.assertEqual(c.di, 42)
c.setType("ds", typeDefaultString("Spam"))
self.assertEqual(c.ds, "Spam")
hasB1 = "b1" in c
self.assertEqual(hasB1, True)
hasX1 = "x1" in c
self.assertEqual(hasX1, False)
if __name__ == "__main__":
unittest.main()
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.