-
Notifications
You must be signed in to change notification settings - Fork 2
/
enc.py
executable file
·452 lines (371 loc) · 14.2 KB
/
enc.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
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
#!/usr/bin/python3
#-*- coding: utf-8 -*-
#copyright 2016 clsergent
#prefs version 2.0.3
#licence GPLv3
#version de test
#this file has been ported in python3 and modified for the purposes of the Theochrone
import io
import datetime
import os
import re
import sys
import _sre
from xml.etree.ElementTree import Element, ElementTree, XML
import xml.dom.minidom as xdm
chemin = os.path.dirname(os.path.abspath(__file__))
programme = os.path.abspath(chemin + '/programme')
sys.path.append(programme)
import adjutoria
import imagines
import phlog
logger = phlog.loggers['console']
class Modele():
"""Une classe modèle pour les types non implémentés."""
def __init__(self,classe='',att={}):
self.classe=classe
self.attributs=att
class PreferencesType:
Element= Element
"""handle conversion from and to XML of the given type
when created, the instance immediately add itself to Preferences types set
PreferencesType.Element can be safely called for getObj and getXML implementation"""
def __init__(self, *newtypes, tag= None, getobj= None, getxml= None):
"""create the new PreferencesType from the given newtype, and tag is used for XML labelling
getobj and getxml are used for conversion from and to XML. If not provided, corresponding methods must be implemented"""
self._types= newtypes
if not tag:
tag= newtypes[0].__name__
self._tag= tag
if callable(getobj):
self.getObj= getobj
if callable(getxml):
self.getXML= getxml
#directly added to Preferences types set
#Preferences.addType(sef)
def getObj(self, item, **kwds):
""""return an instance of _type from an XML Element"""
raise(NotImplementedError)
def getXML(self, obj, **kwds):
"""return an XML Element from an instance of _type"""
raise(NotImplementedError)
def getTag(self):
return self._tag
def getTypes(self):
return self._types
tag= property(getTag, doc='tag used for XML formatting')
types= property(getTypes, doc='types handled')
class PreferencesTypeModele(PreferencesType):
def __init__(self):
PreferencesType.__init__(self, Modele)
def getObj(self, item, **kwds):
obj=Modele()
for child in item.getchildren():
obj.__dict__[child.get('key')]= Preferences.getObj(child)
if obj.classe == 'Images':
objetrenvoye = imagines.Images()
else:
objetrenvoye=getattr(adjutoria,obj.classe)()
objetrenvoye.__dict__=obj.attributs
return objetrenvoye
def getXML(self, obj, **kwds):
item=Element(self.tag, **kwds)
for key, value in obj.__dict__.items():
item.append(Preferences.getXML(value, key=key))
return item
class PreferencesTypeTimedelta(PreferencesType):
def __init__(self):
PreferencesType.__init__(self, datetime.timedelta)
def getObj(self, item, **kwds):
return datetime.timedelta(seconds=float(item.text))
def getXML(self, obj, **kwds):
item=Element(self.tag, **kwds)
item.text=str(obj.total_seconds())
return item
class PreferencesTypeDate(PreferencesType):
def __init__(self):
PreferencesType.__init__(self, datetime.date)
def getObj(self, item, **kwds):
return datetime.date(*map(int,item.split('-')))
def getXML(self, obj, **kwds):
item=Element(self.tag, **kwds)
item.text= obj.isoformat()
return item
class PreferencesTypeString(PreferencesType):
def __init__(self):
PreferencesType.__init__(self, str)
def getObj(self, item, **kwds):
return '' if item.text is None else item.text
#return item.text
def getXML(self, obj, **kwds):
item= Element(self.tag, **kwds)
item.text= obj
return item
class PreferencesTypeInt(PreferencesType):
def __init__(self):
PreferencesType.__init__(self, int)
def getObj(self, item, **kwds):
return int(item.text)
def getXML(self, obj, **kwds):
item= Element(self.tag, **kwds)
item.text= str(obj)
return item
class PreferencesTypeFloat(PreferencesType):
def __init__(self):
PreferencesType.__init__(self, float)
def getObj(self, item, **kwds):
return float(item.text)
def getXML(self, obj, **kwds):
item= Element(self.tag, **kwds)
item.text= str(obj)
return item
class PreferencesTypeBool(PreferencesType):
def __init__(self):
PreferencesType.__init__(self, bool)
def getObj(self, item, **kwds):
return eval(item.text)
def getXML(self, obj, **kwds):
item= Element(self.tag, **kwds)
item.text= str(obj)
return item
class PreferencesTypeNone(PreferencesType):
def __init__(self):
PreferencesType.__init__(self, type(None), tag= 'None')
def getObj(self, item, **kwds):
return None
def getXML(self, obj, **kwds):
item= Element(self.tag, **kwds)
return item
class PreferencesTypeDict(PreferencesType):
def __init__(self):
PreferencesType.__init__(self, dict)
def getObj(self, item, **kwds):
obj= dict()
for child in item.getchildren():
try:
if 'uGly DaTe:' in child.get('key'): # PAucazou made this horrible code when he was a stupid young programmer ; and maybe he is still # BUG
nope, key = child.get('key').split(':')
obj[datetime.date(*map(int,key.split('-')))] = Preferences.getObj(child)
if 'tH1s 1s AN InTEg3r' in child.get('key'):
key = child.get('key')[18:]
obj[int(key)] = Preferences.getObj(child)
elif 'Th1s iS a FlOAt' in child.get('key'):
key = child.get('key')[15:]
obj[float(key)] = Preferences.getObj(child)
elif 'tHIS 1 is a bo0l' in child.get('key'):
key = child.get('key')[16:]
if key == 'True':
obj[True] = Preferences.getObj(child)
else:
obj[False] = Preferences.getObj(child)
else:
obj[child.get('key')]= Preferences.getObj(child)
except ValueError:
obj[child.get('key')]= Preferences.getObj(child)
return obj
def getXML(self, obj, **kwds):
item= Element(self.tag, **kwds)
for key, value in sorted(obj.items()):
if isinstance(key,bool):
key = 'tHIS 1 is a bo0l' + str(key)
elif isinstance(key,int):
key = 'tH1s 1s AN InTEg3r' + str(key)
elif isinstance(key,float):
key = 'Th1s iS a FlOAt' + str(key)
elif isinstance(key,datetime.date):
key = 'uGly DaTe:' + key.isoformat()
item.append(Preferences.getXML(value, key=key))
return item
class PreferencesTypeList(PreferencesType):
def __init__(self):
PreferencesType.__init__(self, list)
def getObj(self, item, **kwds):
obj= list()
for child in item.getchildren():
obj.append(Preferences.getObj(child))
return obj
def getXML(self, obj, **kwds):
item= Element(self.tag, **kwds)
for value in obj:
item.append(Preferences.getXML(value))
return item
class PreferencesTypeTuple(PreferencesType):
def __init__(self):
PreferencesType.__init__(self, tuple)
def getObj(self, item, **kwds):
obj= list()
for child in item.getchildren():
obj.append(Preferences.getObj(child))
return tuple(obj)
def getXML(self, obj, **kwds):
item= Element(self.tag, **kwds)
for value in obj:
item.append(Preferences.getXML(value))
return item
class PreferencesTypeSet(PreferencesType):
def __init__(self):
PreferencesType.__init__(self, set)
def getObj(self, item, **kwds):
obj= set()
for child in item.getchildren():
obj.add(Preferences.getObj(child))
return obj
def getXML(self, obj, **kwds):
item= Element(self.tag, **kwds)
for value in obj:
item.append(Preferences.getXML(value))
return item
class PreferencesTypeTuple(PreferencesType):
def __init__(self):
PreferencesType.__init__(self, tuple)
def getObj(self, item, **kwds):
obj= list()
for child in item.getchildren():
obj.append(Preferences.getObj(child))
return tuple(obj)
def getXML(self, obj, **kwds):
item= Element(self.tag, **kwds)
for value in obj:
item.append(Preferences.getXML(value))
return item
class PreferencesTypeSRE_Pattern(PreferencesType):
retype = type(re.compile('something'))
def __init__(self):
PreferencesType.__init__(self,re.compile)
def getObj(self,item, **kwds):
return re.compile(item.text)
def getXML(self, obj, **kwds):
item= Element(self.tag, **kwds)
item.text = obj.pattern
return item
class Preferences(io.FileIO):
types= {PreferencesTypeString(),
PreferencesTypeInt(),
PreferencesTypeFloat(),
PreferencesTypeNone(),
PreferencesTypeDict(),
PreferencesTypeList(),
PreferencesTypeTuple(),
PreferencesTypeSet(),
PreferencesTypeModele(),
PreferencesTypeTimedelta(),
PreferencesTypeDate(),
PreferencesTypeBool(),
PreferencesTypeSRE_Pattern(),
}
def __init__(self, *args, **kwds):
io.FileIO.__init__(self, *args, **kwds)
def _noIOAccess(func):
def operation(*args, **kwds):
raise(IOError, 'access to IO operations is not allowed')
return operation
@classmethod
def addType(cls, newtype):
"""add a new PreferencesType to the types dictionnary"""
if not isinstance(newtype, PreferencesType):
cls._types.add(newtype)
@classmethod
def removeType(cls, oldtype):
"""remove a PreferencesType form the types dictionnary"""
if oldtype in cls.types:
cls.types.remove(oldtype)
@classmethod
def getType(cls, tag_or_type):
"""return the PreferencesType corresponding to tag_or_obj"""
if isinstance(tag_or_type, str):
for preftype in cls.types:
if tag_or_type == preftype.tag:
return preftype
return False
else:
for preftype in cls.types:
if tag_or_type in preftype.types:
return preftype
return False
def get(self, noerror= False, **kwds):
"""get the content of the file parsed as XML"""
if noerror:
try:
return cls.get(obj, noerror=False, **kwds)
except:
return False
self.seek(0)
raw= io.FileIO.read(self)
return self.gets(raw, noerror)
#except:
return set()
@classmethod
def gets(cls, raw, noerror= False, **kwds):
"""return an object from an XML string"""
if noerror:
try:
return cls.gets(obj, noerror=False, **kwds)
except:
return False
item= XML(raw)
return cls.getObj(item)
def set(self, obj, noerror=False, **kwds):
"""write the obj as XML in the file"""
if noerror:
try:
return cls.set(obj, noerror=False, **kwds)
except:
return False
item= self.getXML(obj)
self.truncate(0)
self.seek(0)
ElementTree(item).write(self, encoding= 'utf-8', xml_declaration=True)
return True
@classmethod
def sets(cls, obj, noerror= False, **kwds):
"""return an XML string fro an object"""
if noerror:
try:
return cls.sets(obj, noerror=False, **kwds)
except:
return False
item= cls.getXML(obj)
file= io.BytesIO()
ElementTree(item).write(file, encoding= 'utf-8', xml_declaration=True)
return file.getvalue()
@classmethod
def getObj(cls, item, **kwds):
""""get obj from an XML Element using types"""
preftype= cls.getType(item.tag)
if not preftype:
raise NotImplementedError('support of {0} has not been implemented yet'.format(item.tag))
else:
return preftype.getObj(item, **kwds)
@classmethod
def getXML(cls, obj, **kwds):
"""get an XML Element from obj using types"""
preftype= cls.getType(type(obj))
if not preftype and isinstance(obj,PreferencesTypeSRE_Pattern.retype):
preftype=cls.getType('compile')
elif not preftype:
try:
obj=Modele(type(obj).__name__,obj.__dict__)
except:
raise NotImplementedError('support of {0} has not been implemented yet'.format(type(obj)))
else:
preftype=cls.getType(type(obj))
return preftype.getXML(obj, **kwds)
#legacy function, should not be used
get_prefs= get
set_prefs= set
get_sprefs= gets
set_sprefs= sets
prefs= property(get, set, doc='access to the file')
def tostring(obj, noerror= False, **kwds):
"""convenient function to get an XML string from a given obj"""
return Preferences.sets(obj, noerror, **kwds)
def fromstring(raw, noerror= False, **kwds):
"""convenient function to get an object from an XML string"""
return Preferences.gets(raw, noerror, **kwds)
def prettyfyxml(file_path):
"""convenient function to make an xml file more readable"""
raw_xml = xdm.parse(file_path).toprettyxml()
with open(file_path,'w') as f:
f.write(raw_xml)
if __name__ == '__main__':
print('this module is not intended to be used standalone')