-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfparse.py
More file actions
601 lines (457 loc) · 18.6 KB
/
confparse.py
File metadata and controls
601 lines (457 loc) · 18.6 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
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
import re,os
from tempfile import mkstemp
class Error(Exception):
"""Base class for ConfigParser exceptions."""
def __init__(self, msg=''):
self.message = msg
Exception.__init__(self, msg)
def __repr__(self):
return self.message
__str__ = __repr__
class NoSectionError(Error):
"""Raised when no section matches a requested option."""
def __init__(self, section):
Error.__init__(self, 'No section: %r' % (section,))
self.section = section
class DuplicateSectionError(Error):
"""Raised when a section is created twice."""
def __init__(self, section):
Error.__init__(self, "Section %r already exists" % section)
self.section = section
class NoOptionError(Error):
"""A requested option was not found."""
def __init__(self, option, section):
Error.__init__(self, "No option %r in section: %r" %
(option, section))
self.option = option
self.section = section
class EvaluationError(Error):
"""Base class for interpolation-related exceptions."""
def __init__(self, option, section, msg):
Error.__init__(self, msg)
self.option = option
self.section = section
class EvaluationMissingOptionError(EvaluationError):
"""A string substitution required a setting which was not available."""
def __init__(self, option, section, rawval, reference):
msg = ("Bad value substitution:\n"
"\tsection: [%s]\n"
"\toption : %s\n"
"\tkey : %s\n"
"\trawval : %s\n"
% (section, option, reference, rawval))
EvaluationError.__init__(self, option, section, msg)
self.reference = reference
class ParsingError(Error):
"""Raised when a configuration file does not follow legal syntax."""
def __init__(self, filename):
Error.__init__(self, 'File contains parsing errors: %s' % filename)
self.filename = filename
self.errors = []
def append(self, lineno, line):
self.errors.append((lineno, line))
self.message += '\n\t[line %2d]: %s' % (lineno, line)
class MissingSectionHeaderError(ParsingError):
"""Raised when a key-value pair is found before any section header."""
def __init__(self, filename, lineno, line):
Error.__init__(
self,
'File contains no section headers.\nfile: %s, line: %d\n%r' %
(filename, lineno, line))
self.filename = filename
self.lineno = lineno
self.line = line
class proxy(object):
"""When you aggregate a 'proxy' to a dikshanary then the
proxy s attribute are the dict s item. Can be convenient"""
# [ off the record, this is still a bit voodoo I must say. Should have a look
# at the optparse module where the idea comes from, in the first place]
def __init__(self, _dict):
object.__setattr__(self, '__dict', _dict)
# The three following functions are the ones that are called when
# you get, set, or delete an attribute of the proxy
def __getattr__(self, item):
return getattr(self, '__dict')[ item ]
def __setattr__(self, item, value):
getattr(self, '__dict')[ item ] = value
def __delattr__(self, item):
del getattr(self, '__dict')[ item ]
class properties(dict):
def __init__(self, _fileordict=None, _order=[], **kwargs):
"""The constructor accepts a filename or a list of filenames. It
can also be a dictionnary or another properties instance. Lastly,
it can accept the entries of the form key1='value1', key2='value2'.
"""
self.dustbin, self.template = [], ""
self.order = _order
self.proxy=proxy(self)
if isinstance( _fileordict, str ) or isinstance( _fileordict, list):
self.template=_fileordict
self.read( _fileordict )
elif hasattr( _fileordict, '__setitem__' ):
self.update( _fileordict )
if hasattr( _fileordict, 'dustbin' ):
self.dustbin = _fileordict.dustbin[:]
if hasattr( _fileordict, 'order' ):
self.order = _fileordict.order[:]
if kwargs:
for k,v in kwargs.items():
self[k] = str( v )
def copy(self):
return properties(self)
line=re.compile("""
(^
\s*
(?P<option> [^\#;]+?)
(\s* (=|:) \s*)
(?P<value> .+?)?
(\s+((\#|;).*)?)?
$)|(^
(\s*(\#|;)+\s*
(?P<cmted> .*))
$)|(^
\s+
(?P<cont> [^\#;]*?)
(\s+(\#|;).*)?
$)""", re.VERBOSE)
variable=re.compile(r'(?<!\\)\$(?P<name>\w+)')
def interpolate(self, value):
"""Recursively evaluates the variables as keys of the
properties instance, and replace them with the corresponding
value. The variables are defined by a dollar sign followed by
alphanumeric characters. If the $ sign is preceded by a \ it
is not a variable. If the variable is not a key of the
instance, a key error is raised."""
if value:
if self.variable.search(value):
try:
return self.variable.sub( lambda m:self.interpolate( self[m.group('name')]) , value)
except RuntimeError:
print "Error: Loop in assignments"
return value.replace("\$","$")
else:
return value.replace("\$","$")
else:
return ''
def get(self, item, default=""):
"""If there is no value in the dict for item, get returns the
'default'. A evaluation of a missing variable raise a KeyError
exception. Variables in values are evaluated. Item and default
can both be list. In this case, get behaves as if it had been called
on each elements of items and returns the lists of values."""
if isinstance(item,list):
was_list = True
else: item, was_list = [ item ], False
if not isinstance(default,list):
default = [ default ]
if len(item)==len(default):
ret = map( lambda i: self.interpolate(dict.get(self, i[0], i[1])), zip (item, default))
else:
ret = [ self.interpolate(dict.get(self, i)) for i in item ]
if was_list:
return ret
else:
return ret[0]
def __setitem__(self, item, value):
"""Sets a value for the item. If the item was in the dustbin,
it is removed from the dustbin"""
if item in self.dustbin:
self.dustbin.remove(item)
dict.__setitem__( self, item, str(value))
def __delitem__(self, item):
"""Suppress the item and value from the instance. The deleted
option is flagged to be skipped when writing or updated a file
so that the option is effectively deleted"""
self.dustbin.append(item)
if item in self:
dict.__delitem__( self, item)
def delete(self, item):
if isinstance(item, list):
map(self.__delitem__, item)
else:
self.__delitem__(item)
return self
def items(self, default={}, **kwargs):
d=default.copy()
d.update(kwargs)
d.update(dict.items(self))
return d
def linerepr ( self, k ) :
if k in self: return k + '=' + self[k].replace('\n','\n\t') + '\n'
else : return ""
def __repr__(self):
"""The read and write methods will update the filename
attribute. This file, if exist, is taken as a template for the
layout and comments. Deleted options are not
represented. Then, keys in the instance but not found in the
file (or if the filename attribute is empty) are added, sorted
by the order attribute. Finally, left options are added
alphabetically."""
def replace_value_in_line (mo, value):
"""Handy function that replace a named group by a string
in the string that the matched object was generated from"""
return mo.string[ :mo.start('value') ] + value.replace( '\n', '\n\t' ) + mo.string[ mo.end('value'): ]
# Because we pop the written lines, we need to pop on a _copy_
a_copy = properties(self)
result=""
try: fp = file( self.template )
except: fp = []
for line in fp:
mo = a_copy.line.match(line)
if not mo:
result += line
continue
option, cont, cmted = mo.group('option', 'cont', 'cmted')
if option and option in a_copy:
result += replace_value_in_line (mo, a_copy[option] )
del a_copy[option]
elif cmted:
mo = a_copy.line.match(cmted)
if not mo:
result += line
continue
option = mo.group( 'option' )
if option and option in a_copy:
result += replace_value_in_line ( mo, a_copy[option] )
del a_copy[option]
else:
result += line
# skip the line whose option is in the dustbin
elif option and option in a_copy.dustbin: pass
# skip the continuation lines, already handled by the 'option' block
elif cont: pass
else: result += line
for k in a_copy.order[:] :
result += a_copy.linerepr( k )
del a_copy[k]
result += ''.join( [ a_copy.linerepr( k ) for k in sorted(a_copy.keys()) ] )
return result
def read(self,filenames=[]):
"""read and parse the list of named configuration files, given
by name. A single filename is also allowed. Non-existing
files are ignored. Return list of successfully read
files. The filename attribute is update with the last element
of the list, so that the write methods can be called with no
argument"""
if isinstance(filenames, basestring):
self._read( file(filenames), filenames)
self.template=filenames
for filename in filenames:
try:
fp = open(filename)
except IOError:
continue
self._read(fp, filename)
fp.close()
self.template=filename
return self.proxy
def _read( self, fp, fn):
"""Parses each line of an open file, and detects options,
values, and continuation lines."""
for l in fp:
m = self.line.match( l )
if m:
option, value, cont = m.group('option', 'value', 'cont')
if option: cur_opt, self[option] = option, value
elif cont: self[cur_opt] += '\n' + cont.lstrip()
def write(self, destination=None, order=None):
"""write can be called with an open file, with a filename, or
without argument. The filename is the destination file, if
missing, the filename attribute is the destination file. If
both are empty, the representation of the instance is written
on stdout"""
if isinstance( destination, basestring):
self.template = destination
fd, tmp = mkstemp()
os.close(fd)
f = file(tmp,'w')
elif isinstance(destination,file):
f = destination
elif self.template:
destination = self.template
fd, tmp = mkstemp()
os.close(fd)
f = file(tmp,'w')
if not self.template:
print repr(self)
else:
f.write(repr(self))
if isinstance(destination, basestring):
f.close()
try:
os.rename(tmp,destination)
except:
open(destination,'w').write(open(tmp).read())
os.unlink(tmp)
apply_to = write
class ini(dict):
# Shortcut to the dict set and del methods (Hosts do no override get)
def dget(self, item): return dict.__getitem__(self, item )
def dset(self, item, value): dict.__setitem__(self, item, value )
def ddel(self, item): dict.__delitem__(self, item )
def __init__(self, _fileordict=None, **kwargs):
self.dustbin, self.defaults, self.template = [], {}, ""
self.proxy=proxy(self)
if type(_fileordict)==str:
self.template=_fileordict
self.read(_fileordict)
elif hasattr(_fileordict,'__setitem__'):
for (k, v) in _fileordict.items():
if hasattr(v, '__setitem__'):
self[k]=v.copy()
else:
self.defaults.update(_fileordict)
if hasattr(_fileordict, 'dustbin'):
self.dustbin = _fileordict.dustbin[:]
if kwargs:
self.defaults.update(kwargs)
line=re.compile('''
(^
\[
(?P<section> .+) \]
(\s+((\#|;).*)?)?
$)|(^
\s*
(?P<option> [^\#;]+?)
(\s* (=|:) \s*)
(?P<value> .+?)?
(\s+((\#|;).*)?)?
$)|(^
(\s*(\#|;)+\s*
(?P<cmted> .*))
$)|(^
\s+
(?P<cont> [^\#;]*?)
(\s+(\#|;).*)?
$)''', re.VERBOSE)
def __setitem__(self, item, value):
item = str( item )
if item in self.dustbin:
self.dustbin.remove(item)
dict.__setitem__(self,item, value)
def __delitem__(self, item):
item = str( item )
self.dustbin.append(item)
if item in self:
dict.__delitem__(self, item)
def get(self, section, option, default=None):
try:
return self[section][option]
except KeyError:
return self.defaults[option]
def simple_line ( self, section, key ) :
if key in self.section:
return key + '=' + a_copy[section][key].replace('\n','\n\t') + '\n'
else : return ""
def __repr__(self):
def replace_value_in_line (mo, value):
return mo.string[ :mo.start('value') ] + value.replace( '\n', '\n\t' ) + mo.string[ mo.end('value'): ]
# Because we pop the written lines, we need to pop on a _copy_
a_copy, result, cur_sect = ini(self), '', ''
try: fp = file( self.template )
except: fp = []
for line in fp :
mo = a_copy.line.match(line)
if not mo:
result += line
continue
# if section then dump the remaining options and supppres the a_copy[cur_sect]
# then only then can you write the option
section, option, cont, cmted = mo.group('section', 'option', 'cont', 'cmted')
if section:
if cur_sect and cur_sect in a_copy:
result += repr ( a_copy[cur_sect] )
del a_copy[cur_sect]
if section not in self.dustbin:
result += line
cur_sect = section
# skip the line whose option is in the dustbin
elif option and option in a_copy[cur_sect].dustbin:
pass
elif option and option in a_copy[cur_sect]:
result += replace_value_in_line (mo, a_copy[cur_sect][option])
del a_copy[cur_sect][option]
elif cmted:
mo = a_copy.line.match( cmted )
if not mo:
result += line
continue
option = mo.group( 'option' )
if option and option in a_copy[cur_sect]:
result += replace_value_in_line (mo, a_copy[cur_sect][option])
del a_copy[cur_sect][option]
else: result += line
# skip the continuation lines, already handled by the 'option' block
elif cont: pass
else: result += line
if cur_sect and cur_sect in a_copy:
result += repr ( a_copy[cur_sect] )
del a_copy[cur_sect]
for section in sorted(a_copy.keys()):
result += '[' + section + ']\n' + repr ( a_copy[section] ) + '\n'
return result
def read(self,filenames):
if isinstance(filenames, basestring):
filenames = [filenames]
read_ok = []
for filename in filenames:
try:
fp = open(filename)
except IOError:
continue
self._read(fp, filename)
fp.close()
read_ok.append(filename)
self.template=filename
return read_ok
def _read( self, fp, fn ):
'''Can read ifcfg files, java properties files as well as ini
files with section, and updates self accordingly'''
for line in fp:
m = self.line.match( line )
if m:
section, option, value, cont = m.group('section', 'option', 'value', 'cont')
if section:
cur_sect = self[section] = properties()
elif option:
cur_sect[option], cur_opt, = value, option
elif cont:
cur_sect[cur_opt] += '\n' + cont.lstrip()
def write(self, destination=None, order=None):
if isinstance( destination, basestring):
self.template = destination
fd, tmp = mkstemp()
os.close(fd)
f = file(tmp,'w')
elif isinstance(destination,file):
f = destination
elif self.template:
destination = self.template
fd, tmp = mkstemp()
os.close(fd)
f = file(tmp,'w')
if not self.template:
repr(self)
else:
f.write(repr(self))
if isinstance(destination, basestring):
f.close()
try:
os.rename(tmp,destination)
except:
open(destination,'w').write(open(tmp,'r').read())
os.unlink(tmp)
if __name__=='__main__':
# je veux un second dict qui contienne les defauts
i=properties( {'abc':'changed','titi':'toutou'}, abd="Trans go#a")
import sys
print i
i.write(sys.stdout)
c=i.read()
print c.titi
print c.abc
c.tata=123
print c.tata
del c.tata
del c.titi
print i