-
Notifications
You must be signed in to change notification settings - Fork 1
/
config.py
1678 lines (1483 loc) · 55.6 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
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2004-2010 by Vinay Sajip. All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this permission notice appear in
# supporting documentation, and that the name of Vinay Sajip
# not be used in advertising or publicity pertaining to distribution
# of the software without specific, written prior permission.
# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""
This is a configuration module for Python.
This module should work under Python versions >= 2.2, and cannot be used with
earlier versions since it uses new-style classes.
Development and testing has only been carried out (so far) on Python 2.3.4 and
Python 2.4.2. See the test module (test_config.py) included in the
U{distribution<http://www.red-dove.com/python_config.html|_blank>} (follow the
download link).
A simple example - with the example configuration file::
messages:
[
{
stream : `sys.stderr`
message: 'Welcome'
name: 'Harry'
}
{
stream : `sys.stdout`
message: 'Welkom'
name: 'Ruud'
}
{
stream : $messages[0].stream
message: 'Bienvenue'
name: Yves
}
]
a program to read the configuration would be::
from config import Config
f = file('simple.cfg')
cfg = Config(f)
for m in cfg.messages:
s = '%s, %s' % (m.message, m.name)
try:
print >> m.stream, s
except IOError, e:
print e
which, when run, would yield the console output::
Welcome, Harry
Welkom, Ruud
Bienvenue, Yves
See U{this tutorial<http://www.red-dove.com/python_config.html|_blank>} for more
information.
@version: 0.3.9
@author: Vinay Sajip
@copyright: Copyright (C) 2004-2010 Vinay Sajip. All Rights Reserved.
@var streamOpener: The default stream opener. This is a factory function which
takes a string (e.g. filename) and returns a stream suitable for reading. If
unable to open the stream, an IOError exception should be thrown.
The default value of this variable is L{defaultStreamOpener}. For an example
of how it's used, see test_config.py (search for streamOpener).
"""
__author__ = "Vinay Sajip <[email protected]>"
__status__ = "alpha"
__version__ = "0.3.9"
__date__ = "11 May 2010"
from types import StringType, UnicodeType
import codecs
import logging
import os
import sys
WORD = 'a'
NUMBER = '9'
STRING = '"'
EOF = ''
LCURLY = '{'
RCURLY = '}'
LBRACK = '['
LBRACK2 = 'a['
RBRACK = ']'
LPAREN = '('
LPAREN2 = '(('
RPAREN = ')'
DOT = '.'
COMMA = ','
COLON = ':'
AT = '@'
PLUS = '+'
MINUS = '-'
STAR = '*'
SLASH = '/'
MOD = '%'
BACKTICK = '`'
DOLLAR = '$'
TRUE = 'True'
FALSE = 'False'
NONE = 'None'
WORDCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_"
if sys.platform == 'win32':
NEWLINE = '\r\n'
elif os.name == 'mac':
NEWLINE = '\r'
else:
NEWLINE = '\n'
try:
import encodings.utf_32
has_utf32 = True
except:
has_utf32 = False
try:
from logging.handlers import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
logger = logging.getLogger(__name__)
if not logger.handlers:
logger.addHandler(NullHandler())
class ConfigInputStream(object):
"""
An input stream which can read either ANSI files with default encoding
or Unicode files with BOMs.
Handles UTF-8, UTF-16LE, UTF-16BE. Could handle UTF-32 if Python had
built-in support.
"""
def __init__(self, stream):
"""
Initialize an instance.
@param stream: The underlying stream to be read. Should be seekable.
@type stream: A stream (file-like object).
"""
encoding = None
signature = stream.read(4)
used = -1
if has_utf32:
if signature == codecs.BOM_UTF32_LE:
encoding = 'utf-32le'
elif signature == codecs.BOM_UTF32_BE:
encoding = 'utf-32be'
if encoding is None:
if signature[:3] == codecs.BOM_UTF8:
used = 3
encoding = 'utf-8'
elif signature[:2] == codecs.BOM_UTF16_LE:
used = 2
encoding = 'utf-16le'
elif signature[:2] == codecs.BOM_UTF16_BE:
used = 2
encoding = 'utf-16be'
else:
used = 0
if used >= 0:
stream.seek(used)
if encoding:
reader = codecs.getreader(encoding)
stream = reader(stream)
self.stream = stream
self.encoding = encoding
def read(self, size):
if (size == 0) or (self.encoding is None):
rv = self.stream.read(size)
else:
rv = u''
while size > 0:
rv += self.stream.read(1)
size -= 1
return rv
def close(self):
self.stream.close()
def readline(self):
if self.encoding is None:
line = ''
else:
line = u''
while True:
c = self.stream.read(1)
if c:
line += c
if c == '\n':
break
return line
class ConfigOutputStream(object):
"""
An output stream which can write either ANSI files with default encoding
or Unicode files with BOMs.
Handles UTF-8, UTF-16LE, UTF-16BE. Could handle UTF-32 if Python had
built-in support.
"""
def __init__(self, stream, encoding=None):
"""
Initialize an instance.
@param stream: The underlying stream to be written.
@type stream: A stream (file-like object).
@param encoding: The desired encoding.
@type encoding: str
"""
if encoding is not None:
encoding = str(encoding).lower()
self.encoding = encoding
if encoding == "utf-8":
stream.write(codecs.BOM_UTF8)
elif encoding == "utf-16be":
stream.write(codecs.BOM_UTF16_BE)
elif encoding == "utf-16le":
stream.write(codecs.BOM_UTF16_LE)
elif encoding == "utf-32be":
stream.write(codecs.BOM_UTF32_BE)
elif encoding == "utf-32le":
stream.write(codecs.BOM_UTF32_LE)
if encoding is not None:
writer = codecs.getwriter(encoding)
stream = writer(stream)
self.stream = stream
def write(self, data):
self.stream.write(data)
def flush(self):
self.stream.flush()
def close(self):
self.stream.close()
def defaultStreamOpener(name):
"""
This function returns a read-only stream, given its name. The name passed
in should correspond to an existing stream, otherwise an exception will be
raised.
This is the default value of L{streamOpener}; assign your own callable to
streamOpener to return streams based on names. For example, you could use
urllib2.urlopen().
@param name: The name of a stream, most commonly a file name.
@type name: str
@return: A stream with the specified name.
@rtype: A read-only stream (file-like object)
"""
return ConfigInputStream(file(name, 'rb'))
streamOpener = None
class ConfigError(Exception):
"""
This is the base class of exceptions raised by this module.
"""
pass
class ConfigFormatError(ConfigError):
"""
This is the base class of exceptions raised due to syntax errors in
configurations.
"""
pass
class ConfigResolutionError(ConfigError):
"""
This is the base class of exceptions raised due to semantic errors in
configurations.
"""
pass
def isWord(s):
"""
See if a passed-in value is an identifier. If the value passed in is not a
string, False is returned. An identifier consists of alphanumerics or
underscore characters.
Examples::
isWord('a word') ->False
isWord('award') -> True
isWord(9) -> False
isWord('a_b_c_') ->True
@note: isWord('9abc') will return True - not exactly correct, but adequate
for the way it's used here.
@param s: The name to be tested
@type s: any
@return: True if a word, else False
@rtype: bool
"""
if type(s) != type(''):
return False
s = s.replace('_', '')
return s.isalnum()
def makePath(prefix, suffix):
"""
Make a path from a prefix and suffix.
Examples::
makePath('', 'suffix') -> 'suffix'
makePath('prefix', 'suffix') -> 'prefix.suffix'
makePath('prefix', '[1]') -> 'prefix[1]'
@param prefix: The prefix to use. If it evaluates as false, the suffix
is returned.
@type prefix: str
@param suffix: The suffix to use. It is either an identifier or an
index in brackets.
@type suffix: str
@return: The path concatenation of prefix and suffix, with a
dot if the suffix is not a bracketed index.
@rtype: str
"""
if not prefix:
rv = suffix
elif suffix[0] == '[':
rv = prefix + suffix
else:
rv = prefix + '.' + suffix
return rv
class Container(object):
"""
This internal class is the base class for mappings and sequences.
@ivar path: A string which describes how to get
to this instance from the root of the hierarchy.
Example::
a.list.of[1].or['more'].elements
"""
def __init__(self, parent):
"""
Initialize an instance.
@param parent: The parent of this instance in the hierarchy.
@type parent: A L{Container} instance.
"""
object.__setattr__(self, 'parent', parent)
def setPath(self, path):
"""
Set the path for this instance.
@param path: The path - a string which describes how to get
to this instance from the root of the hierarchy.
@type path: str
"""
object.__setattr__(self, 'path', path)
def evaluate(self, item):
"""
Evaluate items which are instances of L{Reference} or L{Expression}.
L{Reference} instances are evaluated using L{Reference.resolve},
and L{Expression} instances are evaluated using
L{Expression.evaluate}.
@param item: The item to be evaluated.
@type item: any
@return: If the item is an instance of L{Reference} or L{Expression},
the evaluated value is returned, otherwise the item is returned
unchanged.
"""
if isinstance(item, Reference):
item = item.resolve(self)
elif isinstance(item, Expression):
item = item.evaluate(self)
return item
def writeToStream(self, stream, indent, container):
"""
Write this instance to a stream at the specified indentation level.
Should be redefined in subclasses.
@param stream: The stream to write to
@type stream: A writable stream (file-like object)
@param indent: The indentation level
@type indent: int
@param container: The container of this instance
@type container: L{Container}
@raise NotImplementedError: If a subclass does not override this
"""
raise NotImplementedError
def writeValue(self, value, stream, indent):
if isinstance(self, Mapping):
indstr = ' '
else:
indstr = indent * ' '
if isinstance(value, Reference) or isinstance(value, Expression):
stream.write('%s%r%s' % (indstr, value, NEWLINE))
else:
if (type(value) is StringType): # and not isWord(value):
value = repr(value)
stream.write('%s%s%s' % (indstr, value, NEWLINE))
class Mapping(Container):
"""
This internal class implements key-value mappings in configurations.
"""
def __init__(self, parent=None):
"""
Initialize an instance.
@param parent: The parent of this instance in the hierarchy.
@type parent: A L{Container} instance.
"""
Container.__init__(self, parent)
object.__setattr__(self, 'path', '')
object.__setattr__(self, 'data', {})
object.__setattr__(self, 'order', []) # to preserve ordering
object.__setattr__(self, 'comments', {})
def __delitem__(self, key):
"""
Remove an item
"""
data = object.__getattribute__(self, 'data')
if key not in data:
raise AttributeError(key)
order = object.__getattribute__(self, 'order')
comments = object.__getattribute__(self, 'comments')
del data[key]
order.remove(key)
del comments[key]
def __getitem__(self, key):
data = object.__getattribute__(self, 'data')
if key not in data:
raise AttributeError(key)
rv = data[key]
return self.evaluate(rv)
__getattr__ = __getitem__
def __getattribute__(self, name):
if name == "__dict__":
return {}
if name in ["__methods__", "__members__"]:
return []
#if name == "__class__":
# return ''
data = object.__getattribute__(self, "data")
useData = data.has_key(name)
if useData:
rv = getattr(data, name)
else:
rv = object.__getattribute__(self, name)
if rv is None:
raise AttributeError(name)
return rv
def iteritems(self):
for key in self.keys():
yield(key, self[key])
raise StopIteration
def __contains__(self, item):
order = object.__getattribute__(self, 'order')
return item in order
def addMapping(self, key, value, comment, setting=False):
"""
Add a key-value mapping with a comment.
@param key: The key for the mapping.
@type key: str
@param value: The value for the mapping.
@type value: any
@param comment: The comment for the key (can be None).
@type comment: str
@param setting: If True, ignore clashes. This is set
to true when called from L{__setattr__}.
@raise ConfigFormatError: If an existing key is seen
again and setting is False.
"""
data = object.__getattribute__(self, 'data')
order = object.__getattribute__(self, 'order')
comments = object.__getattribute__(self, 'comments')
data[key] = value
if key not in order:
order.append(key)
elif not setting:
raise ConfigFormatError("repeated key: %s" % key)
comments[key] = comment
def __setattr__(self, name, value):
self.addMapping(name, value, None, True)
__setitem__ = __setattr__
def keys(self):
"""
Return the keys in a similar way to a dictionary.
"""
return object.__getattribute__(self, 'order')
def get(self, key, default=None):
"""
Allows a dictionary-style get operation.
"""
if key in self:
return self[key]
return default
def __str__(self):
return str(object.__getattribute__(self, 'data'))
def __repr__(self):
return repr(object.__getattribute__(self, 'data'))
def __len__(self):
return len(object.__getattribute__(self, 'order'))
def __iter__(self):
return self.iterkeys()
def iterkeys(self):
order = object.__getattribute__(self, 'order')
return order.__iter__()
def writeToStream(self, stream, indent, container):
"""
Write this instance to a stream at the specified indentation level.
Should be redefined in subclasses.
@param stream: The stream to write to
@type stream: A writable stream (file-like object)
@param indent: The indentation level
@type indent: int
@param container: The container of this instance
@type container: L{Container}
"""
indstr = indent * ' '
if len(self) == 0:
stream.write(' { }%s' % NEWLINE)
else:
if isinstance(container, Mapping):
stream.write(NEWLINE)
stream.write('%s{%s' % (indstr, NEWLINE))
self.save(stream, indent + 1)
stream.write('%s}%s' % (indstr, NEWLINE))
def save(self, stream, indent=0):
"""
Save this configuration to the specified stream.
@param stream: A stream to which the configuration is written.
@type stream: A write-only stream (file-like object).
@param indent: The indentation level for the output.
@type indent: int
"""
indstr = indent * ' '
order = object.__getattribute__(self, 'order')
data = object.__getattribute__(self, 'data')
maxlen = 0 # max(map(lambda x: len(x), order))
for key in order:
comment = self.comments[key]
if isWord(key):
skey = key
else:
skey = repr(key)
if comment:
stream.write('%s#%s' % (indstr, comment))
stream.write('%s%-*s :' % (indstr, maxlen, skey))
value = data[key]
if isinstance(value, Container):
value.writeToStream(stream, indent, self)
else:
self.writeValue(value, stream, indent)
class Config(Mapping):
"""
This class represents a configuration, and is the only one which clients
need to interface to, under normal circumstances.
"""
class Namespace(object):
"""
This internal class is used for implementing default namespaces.
An instance acts as a namespace.
"""
def __init__(self):
self.sys = sys
self.os = os
def __repr__(self):
return "<Namespace('%s')>" % ','.join(self.__dict__.keys())
def __init__(self, streamOrFile=None, parent=None):
"""
Initializes an instance.
@param streamOrFile: If specified, causes this instance to be loaded
from the stream (by calling L{load}). If a string is provided, it is
passed to L{streamOpener} to open a stream. Otherwise, the passed
value is assumed to be a stream and used as is.
@type streamOrFile: A readable stream (file-like object) or a name.
@param parent: If specified, this becomes the parent of this instance
in the configuration hierarchy.
@type parent: a L{Container} instance.
"""
Mapping.__init__(self, parent)
object.__setattr__(self, 'reader', ConfigReader(self))
object.__setattr__(self, 'namespaces', [Config.Namespace()])
object.__setattr__(self, 'resolving', set())
if streamOrFile is not None:
if isinstance(streamOrFile, StringType) or isinstance(streamOrFile, UnicodeType):
global streamOpener
if streamOpener is None:
streamOpener = defaultStreamOpener
streamOrFile = streamOpener(streamOrFile)
load = object.__getattribute__(self, "load")
load(streamOrFile)
def load(self, stream):
"""
Load the configuration from the specified stream. Multiple streams can
be used to populate the same instance, as long as there are no
clashing keys. The stream is closed.
@param stream: A stream from which the configuration is read.
@type stream: A read-only stream (file-like object).
@raise ConfigError: if keys in the loaded configuration clash with
existing keys.
@raise ConfigFormatError: if there is a syntax error in the stream.
"""
reader = object.__getattribute__(self, 'reader')
#object.__setattr__(self, 'root', reader.load(stream))
reader.load(stream)
stream.close()
def addNamespace(self, ns, name=None):
"""
Add a namespace to this configuration which can be used to evaluate
(resolve) dotted-identifier expressions.
@param ns: The namespace to be added.
@type ns: A module or other namespace suitable for passing as an
argument to vars().
@param name: A name for the namespace, which, if specified, provides
an additional level of indirection.
@type name: str
"""
namespaces = object.__getattribute__(self, 'namespaces')
if name is None:
namespaces.append(ns)
else:
setattr(namespaces[0], name, ns)
def removeNamespace(self, ns, name=None):
"""
Remove a namespace added with L{addNamespace}.
@param ns: The namespace to be removed.
@param name: The name which was specified when L{addNamespace} was
called.
@type name: str
"""
namespaces = object.__getattribute__(self, 'namespaces')
if name is None:
namespaces.remove(ns)
else:
delattr(namespaces[0], name)
def save(self, stream, indent=0):
"""
Save this configuration to the specified stream. The stream is
closed if this is the top-level configuration in the hierarchy.
L{Mapping.save} is called to do all the work.
@param stream: A stream to which the configuration is written.
@type stream: A write-only stream (file-like object).
@param indent: The indentation level for the output.
@type indent: int
"""
Mapping.save(self, stream, indent)
if indent == 0:
stream.close()
def getByPath(self, path):
"""
Obtain a value in the configuration via its path.
@param path: The path of the required value
@type path: str
@return the value at the specified path.
@rtype: any
@raise ConfigError: If the path is invalid
"""
s = 'self.' + path
try:
return eval(s)
except Exception, e:
raise ConfigError(str(e))
class Sequence(Container):
"""
This internal class implements a value which is a sequence of other values.
"""
class SeqIter(object):
"""
This internal class implements an iterator for a L{Sequence} instance.
"""
def __init__(self, seq):
self.seq = seq
self.limit = len(object.__getattribute__(seq, 'data'))
self.index = 0
def __iter__(self):
return self
def next(self):
if self.index >= self.limit:
raise StopIteration
rv = self.seq[self.index]
self.index += 1
return rv
def __init__(self, parent=None):
"""
Initialize an instance.
@param parent: The parent of this instance in the hierarchy.
@type parent: A L{Container} instance.
"""
Container.__init__(self, parent)
object.__setattr__(self, 'data', [])
object.__setattr__(self, 'comments', [])
def append(self, item, comment):
"""
Add an item to the sequence.
@param item: The item to add.
@type item: any
@param comment: A comment for the item.
@type comment: str
"""
data = object.__getattribute__(self, 'data')
comments = object.__getattribute__(self, 'comments')
data.append(item)
comments.append(comment)
def __getitem__(self, index):
data = object.__getattribute__(self, 'data')
try:
rv = data[index]
except (IndexError, KeyError, TypeError):
raise ConfigResolutionError('%r is not a valid index for %r' % (index, object.__getattribute__(self, 'path')))
if not isinstance(rv, list):
rv = self.evaluate(rv)
else:
# deal with a slice
result = []
for a in rv:
result.append(self.evaluate(a))
rv = result
return rv
def __iter__(self):
return Sequence.SeqIter(self)
def __repr__(self):
return repr(object.__getattribute__(self, 'data'))
def __str__(self):
return str(self[:]) # using the slice evaluates the contents
def __len__(self):
return len(object.__getattribute__(self, 'data'))
def writeToStream(self, stream, indent, container):
"""
Write this instance to a stream at the specified indentation level.
Should be redefined in subclasses.
@param stream: The stream to write to
@type stream: A writable stream (file-like object)
@param indent: The indentation level
@type indent: int
@param container: The container of this instance
@type container: L{Container}
"""
indstr = indent * ' '
if len(self) == 0:
stream.write(' [ ]%s' % NEWLINE)
else:
if isinstance(container, Mapping):
stream.write(NEWLINE)
stream.write('%s[%s' % (indstr, NEWLINE))
self.save(stream, indent + 1)
stream.write('%s]%s' % (indstr, NEWLINE))
def save(self, stream, indent):
"""
Save this instance to the specified stream.
@param stream: A stream to which the configuration is written.
@type stream: A write-only stream (file-like object).
@param indent: The indentation level for the output, > 0
@type indent: int
"""
if indent == 0:
raise ConfigError("sequence cannot be saved as a top-level item")
data = object.__getattribute__(self, 'data')
comments = object.__getattribute__(self, 'comments')
indstr = indent * ' '
for i in xrange(0, len(data)):
value = data[i]
comment = comments[i]
if comment:
stream.write('%s#%s' % (indstr, comment))
if isinstance(value, Container):
value.writeToStream(stream, indent, self)
else:
self.writeValue(value, stream, indent)
class Reference(object):
"""
This internal class implements a value which is a reference to another value.
"""
def __init__(self, config, type, ident):
"""
Initialize an instance.
@param config: The configuration which contains this reference.
@type config: A L{Config} instance.
@param type: The type of reference.
@type type: BACKTICK or DOLLAR
@param ident: The identifier which starts the reference.
@type ident: str
"""
self.config = config
self.type = type
self.elements = [ident]
def addElement(self, type, ident):
"""
Add an element to the reference.
@param type: The type of reference.
@type type: BACKTICK or DOLLAR
@param ident: The identifier which continues the reference.
@type ident: str
"""
self.elements.append((type, ident))
def findConfig(self, container):
"""
Find the closest enclosing configuration to the specified container.
@param container: The container to start from.
@type container: L{Container}
@return: The closest enclosing configuration, or None.
@rtype: L{Config}
"""
while (container is not None) and not isinstance(container, Config):
container = object.__getattribute__(container, 'parent')
return container
def resolve(self, container):
"""
Resolve this instance in the context of a container.
@param container: The container to resolve from.
@type container: L{Container}
@return: The resolved value.
@rtype: any
@raise ConfigResolutionError: If resolution fails.
"""
rv = None
path = object.__getattribute__(container, 'path')
current = self.findConfig(container)
while current is not None:
if self.type == BACKTICK:
namespaces = object.__getattribute__(current, 'namespaces')
found = False
s = str(self)[1:-1]
for ns in namespaces:
try:
try:
rv = eval(s, vars(ns))
except TypeError: #Python 2.7 - vars is a dictproxy
rv = eval(s, {}, vars(ns))
found = True
break
except:
logger.debug("unable to resolve %r in %r", s, ns)
pass
if found:
break
else:
firstkey = self.elements[0]
if firstkey in current.resolving:
current.resolving.remove(firstkey)
raise ConfigResolutionError("Circular reference: %r" % firstkey)
current.resolving.add(firstkey)
key = firstkey
try:
rv = current[key]
for item in self.elements[1:]:
key = item[1]
rv = rv[key]
current.resolving.remove(firstkey)
break
except ConfigResolutionError:
raise
except:
logger.debug("Unable to resolve %r: %s", key, sys.exc_info()[1])
rv = None
pass
current.resolving.discard(firstkey)
current = self.findConfig(object.__getattribute__(current, 'parent'))
if current is None:
raise ConfigResolutionError("unable to evaluate %r in the configuration %s" % (self, path))
return rv
def __str__(self):
s = self.elements[0]
for tt, tv in self.elements[1:]:
if tt == DOT:
s += '.%s' % tv
else:
s += '[%r]' % tv
if self.type == BACKTICK:
return BACKTICK + s + BACKTICK
else:
return DOLLAR + s
def __repr__(self):
return self.__str__()
class Expression(object):
"""
This internal class implements a value which is obtained by evaluating an expression.
"""
def __init__(self, op, lhs, rhs):
"""
Initialize an instance.
@param op: the operation expressed in the expression.
@type op: PLUS, MINUS, STAR, SLASH, MOD
@param lhs: the left-hand-side operand of the expression.
@type lhs: any Expression or primary value.
@param rhs: the right-hand-side operand of the expression.
@type rhs: any Expression or primary value.
"""
self.op = op
self.lhs = lhs
self.rhs = rhs
def __str__(self):
return '%r %s %r' % (self.lhs, self.op, self.rhs)
def __repr__(self):
return self.__str__()
def evaluate(self, container):
"""
Evaluate this instance in the context of a container.