~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/util/configobj/configobj.py

  • Committer: Patch Queue Manager
  • Date: 2016-02-01 19:13:13 UTC
  • mfrom: (6614.2.2 trunk)
  • Revision ID: pqm@pqm.ubuntu.com-20160201191313-wdfvmfff1djde6oq
(vila) Release 2.7.0 (Vincent Ladeuil)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# configobj.py
2
2
# A config file reader/writer that supports nested sections in config files.
3
 
# Copyright (C) 2005 Michael Foord, Nicola Larosa
 
3
# Copyright (C) 2005-2009 Michael Foord, Nicola Larosa
4
4
# E-mail: fuzzyman AT voidspace DOT org DOT uk
5
5
#         nico AT tekNico DOT net
6
6
 
16
16
# http://lists.sourceforge.net/lists/listinfo/configobj-develop
17
17
# Comments, suggestions and bug reports welcome.
18
18
 
19
 
from __future__ import generators
20
19
 
21
 
"""
22
 
    >>> z = ConfigObj()
23
 
    >>> z['a'] = 'a'
24
 
    >>> z['sect'] = {
25
 
    ...    'subsect': {
26
 
    ...         'a': 'fish',
27
 
    ...         'b': 'wobble',
28
 
    ...     },
29
 
    ...     'member': 'value',
30
 
    ... }
31
 
    >>> x = ConfigObj(z.write())
32
 
    >>> z == x
33
 
    1
34
 
"""
 
20
from __future__ import absolute_import
35
21
 
36
22
import sys
37
 
INTP_VER = sys.version_info[:2]
38
 
if INTP_VER < (2, 2):
39
 
    raise RuntimeError("Python v.2.2 or later needed")
40
 
 
41
 
import os, re
42
 
from types import StringTypes
43
 
from warnings import warn
44
 
from codecs import BOM_UTF8, BOM_UTF16, BOM_UTF16_BE, BOM_UTF16_LE
 
23
import os
 
24
import re
 
25
 
 
26
compiler = None
 
27
# Bzr modification: Disabled import of 'compiler' module
 
28
# bzr doesn't use the 'unrepr' feature of configobj, so importing compiler just
 
29
# wastes several milliseconds on every single bzr invocation.
 
30
#   -- Andrew Bennetts, 2008-10-14
 
31
#try:
 
32
#    import compiler
 
33
#except ImportError:
 
34
#    # for IronPython
 
35
#    pass
 
36
 
 
37
 
 
38
try:
 
39
    from codecs import BOM_UTF8, BOM_UTF16, BOM_UTF16_BE, BOM_UTF16_LE
 
40
except ImportError:
 
41
    # Python 2.2 does not have these
 
42
    # UTF-8
 
43
    BOM_UTF8 = '\xef\xbb\xbf'
 
44
    # UTF-16, little endian
 
45
    BOM_UTF16_LE = '\xff\xfe'
 
46
    # UTF-16, big endian
 
47
    BOM_UTF16_BE = '\xfe\xff'
 
48
    if sys.byteorder == 'little':
 
49
        # UTF-16, native endianness
 
50
        BOM_UTF16 = BOM_UTF16_LE
 
51
    else:
 
52
        # UTF-16, native endianness
 
53
        BOM_UTF16 = BOM_UTF16_BE
45
54
 
46
55
# A dictionary mapping BOM to
47
56
# the encoding to decode with, and what to set the
82
91
    None: BOM_UTF8
83
92
    }
84
93
 
85
 
try:
86
 
    from validate import VdtMissingValue
87
 
except ImportError:
88
 
    VdtMissingValue = None
 
94
 
 
95
def match_utf8(encoding):
 
96
    return BOM_LIST.get(encoding.lower()) == 'utf_8'
 
97
 
 
98
 
 
99
# Quote strings used for writing values
 
100
squot = "'%s'"
 
101
dquot = '"%s"'
 
102
noquot = "%s"
 
103
wspace_plus = ' \r\n\v\t\'"'
 
104
tsquot = '"""%s"""'
 
105
tdquot = "'''%s'''"
89
106
 
90
107
try:
91
108
    enumerate
97
114
            i += 1
98
115
            yield i, item
99
116
 
100
 
try:
101
 
    True, False
102
 
except NameError:
103
 
    True, False = 1, 0
104
 
 
105
 
 
106
 
__version__ = '4.2.0beta2'
 
117
# Sentinel for use in getattr calls to replace hasattr
 
118
MISSING = object()
 
119
 
 
120
__version__ = '4.6.0'
107
121
 
108
122
__revision__ = '$Id: configobj.py 156 2006-01-31 14:57:08Z fuzzyman $'
109
123
 
110
124
__docformat__ = "restructuredtext en"
111
125
 
112
 
# NOTE: Does it make sense to have the following in __all__ ?
113
 
# NOTE: DEFAULT_INDENT_TYPE, NUM_INDENT_SPACES, MAX_INTERPOL_DEPTH
114
 
# NOTE: If used as from configobj import...
115
 
# NOTE: They are effectively read only
116
126
__all__ = (
117
127
    '__version__',
118
128
    'DEFAULT_INDENT_TYPE',
119
 
    'NUM_INDENT_SPACES',
120
 
    'MAX_INTERPOL_DEPTH',
 
129
    'DEFAULT_INTERPOLATION',
121
130
    'ConfigObjError',
122
131
    'NestingError',
123
132
    'ParseError',
126
135
    'ConfigObj',
127
136
    'SimpleVal',
128
137
    'InterpolationError',
129
 
    'InterpolationDepthError',
 
138
    'InterpolationLoopError',
130
139
    'MissingInterpolationOption',
131
140
    'RepeatSectionError',
 
141
    'ReloadError',
 
142
    'UnreprError',
 
143
    'UnknownType',
132
144
    '__docformat__',
133
145
    'flatten_errors',
134
146
)
135
147
 
136
 
DEFAULT_INDENT_TYPE = ' '
137
 
NUM_INDENT_SPACES = 4
 
148
DEFAULT_INTERPOLATION = 'configparser'
 
149
DEFAULT_INDENT_TYPE = '    '
138
150
MAX_INTERPOL_DEPTH = 10
139
151
 
140
152
OPTION_DEFAULTS = {
149
161
    'indent_type': None,
150
162
    'encoding': None,
151
163
    'default_encoding': None,
 
164
    'unrepr': False,
 
165
    'write_empty_values': False,
152
166
}
153
167
 
 
168
 
 
169
 
 
170
def getObj(s):
 
171
    s = "a=" + s
 
172
    if compiler is None:
 
173
        raise ImportError('compiler module not available')
 
174
    p = compiler.parse(s)
 
175
    return p.getChildren()[1].getChildren()[0].getChildren()[1]
 
176
 
 
177
 
 
178
class UnknownType(Exception):
 
179
    pass
 
180
 
 
181
 
 
182
class Builder(object):
 
183
 
 
184
    def build(self, o):
 
185
        m = getattr(self, 'build_' + o.__class__.__name__, None)
 
186
        if m is None:
 
187
            raise UnknownType(o.__class__.__name__)
 
188
        return m(o)
 
189
 
 
190
    def build_List(self, o):
 
191
        return map(self.build, o.getChildren())
 
192
 
 
193
    def build_Const(self, o):
 
194
        return o.value
 
195
 
 
196
    def build_Dict(self, o):
 
197
        d = {}
 
198
        i = iter(map(self.build, o.getChildren()))
 
199
        for el in i:
 
200
            d[el] = i.next()
 
201
        return d
 
202
 
 
203
    def build_Tuple(self, o):
 
204
        return tuple(self.build_List(o))
 
205
 
 
206
    def build_Name(self, o):
 
207
        if o.name == 'None':
 
208
            return None
 
209
        if o.name == 'True':
 
210
            return True
 
211
        if o.name == 'False':
 
212
            return False
 
213
 
 
214
        # An undefined Name
 
215
        raise UnknownType('Undefined Name')
 
216
 
 
217
    def build_Add(self, o):
 
218
        real, imag = map(self.build_Const, o.getChildren())
 
219
        try:
 
220
            real = float(real)
 
221
        except TypeError:
 
222
            raise UnknownType('Add')
 
223
        if not isinstance(imag, complex) or imag.real != 0.0:
 
224
            raise UnknownType('Add')
 
225
        return real+imag
 
226
 
 
227
    def build_Getattr(self, o):
 
228
        parent = self.build(o.expr)
 
229
        return getattr(parent, o.attrname)
 
230
 
 
231
    def build_UnarySub(self, o):
 
232
        return -self.build_Const(o.getChildren()[0])
 
233
 
 
234
    def build_UnaryAdd(self, o):
 
235
        return self.build_Const(o.getChildren()[0])
 
236
 
 
237
 
 
238
_builder = Builder()
 
239
 
 
240
 
 
241
def unrepr(s):
 
242
    if not s:
 
243
        return s
 
244
    return _builder.build(getObj(s))
 
245
 
 
246
 
 
247
 
154
248
class ConfigObjError(SyntaxError):
155
249
    """
156
250
    This is the base class for all errors that ConfigObj raises.
157
251
    It is a subclass of SyntaxError.
158
 
    
159
 
    >>> raise ConfigObjError
160
 
    Traceback (most recent call last):
161
 
    ConfigObjError
162
252
    """
163
253
    def __init__(self, message='', line_number=None, line=''):
164
254
        self.line = line
165
255
        self.line_number = line_number
166
 
        self.message = message
167
256
        SyntaxError.__init__(self, message)
168
257
 
 
258
 
169
259
class NestingError(ConfigObjError):
170
260
    """
171
261
    This error indicates a level of nesting that doesn't match.
172
 
    
173
 
    >>> raise NestingError
174
 
    Traceback (most recent call last):
175
 
    NestingError
176
262
    """
177
263
 
 
264
 
178
265
class ParseError(ConfigObjError):
179
266
    """
180
267
    This error indicates that a line is badly written.
181
268
    It is neither a valid ``key = value`` line,
182
269
    nor a valid section marker line.
183
 
    
184
 
    >>> raise ParseError
185
 
    Traceback (most recent call last):
186
 
    ParseError
187
 
    """
 
270
    """
 
271
 
 
272
 
 
273
class ReloadError(IOError):
 
274
    """
 
275
    A 'reload' operation failed.
 
276
    This exception is a subclass of ``IOError``.
 
277
    """
 
278
    def __init__(self):
 
279
        IOError.__init__(self, 'reload failed, filename is not set.')
 
280
 
188
281
 
189
282
class DuplicateError(ConfigObjError):
190
283
    """
191
284
    The keyword or section specified already exists.
192
 
    
193
 
    >>> raise DuplicateError
194
 
    Traceback (most recent call last):
195
 
    DuplicateError
196
285
    """
197
286
 
 
287
 
198
288
class ConfigspecError(ConfigObjError):
199
289
    """
200
290
    An error occured whilst parsing a configspec.
201
 
    
202
 
    >>> raise ConfigspecError
203
 
    Traceback (most recent call last):
204
 
    ConfigspecError
205
291
    """
206
292
 
 
293
 
207
294
class InterpolationError(ConfigObjError):
208
295
    """Base class for the two interpolation errors."""
209
296
 
210
 
class InterpolationDepthError(InterpolationError):
 
297
 
 
298
class InterpolationLoopError(InterpolationError):
211
299
    """Maximum interpolation depth exceeded in string interpolation."""
212
300
 
213
301
    def __init__(self, option):
214
 
        """
215
 
        >>> raise InterpolationDepthError('yoda')
216
 
        Traceback (most recent call last):
217
 
        InterpolationDepthError: max interpolation depth exceeded in value "yoda".
218
 
        """
219
302
        InterpolationError.__init__(
220
303
            self,
221
 
            'max interpolation depth exceeded in value "%s".' % option)
 
304
            'interpolation loop detected in value "%s".' % option)
 
305
 
222
306
 
223
307
class RepeatSectionError(ConfigObjError):
224
308
    """
225
309
    This error indicates additional sections in a section with a
226
310
    ``__many__`` (repeated) section.
227
 
    
228
 
    >>> raise RepeatSectionError
229
 
    Traceback (most recent call last):
230
 
    RepeatSectionError
231
311
    """
232
312
 
 
313
 
233
314
class MissingInterpolationOption(InterpolationError):
234
315
    """A value specified for interpolation was missing."""
235
316
 
236
317
    def __init__(self, option):
237
 
        """
238
 
        >>> raise MissingInterpolationOption('yoda')
239
 
        Traceback (most recent call last):
240
 
        MissingInterpolationOption: missing option "yoda" in interpolation.
241
 
        """
242
318
        InterpolationError.__init__(
243
319
            self,
244
320
            'missing option "%s" in interpolation.' % option)
245
321
 
 
322
 
 
323
class UnreprError(ConfigObjError):
 
324
    """An error parsing in unrepr mode."""
 
325
 
 
326
 
 
327
 
 
328
class InterpolationEngine(object):
 
329
    """
 
330
    A helper class to help perform string interpolation.
 
331
 
 
332
    This class is an abstract base class; its descendants perform
 
333
    the actual work.
 
334
    """
 
335
 
 
336
    # compiled regexp to use in self.interpolate()
 
337
    _KEYCRE = re.compile(r"%\(([^)]*)\)s")
 
338
 
 
339
    def __init__(self, section):
 
340
        # the Section instance that "owns" this engine
 
341
        self.section = section
 
342
 
 
343
 
 
344
    def interpolate(self, key, value):
 
345
        def recursive_interpolate(key, value, section, backtrail):
 
346
            """The function that does the actual work.
 
347
 
 
348
            ``value``: the string we're trying to interpolate.
 
349
            ``section``: the section in which that string was found
 
350
            ``backtrail``: a dict to keep track of where we've been,
 
351
            to detect and prevent infinite recursion loops
 
352
 
 
353
            This is similar to a depth-first-search algorithm.
 
354
            """
 
355
            # Have we been here already?
 
356
            if (key, section.name) in backtrail:
 
357
                # Yes - infinite loop detected
 
358
                raise InterpolationLoopError(key)
 
359
            # Place a marker on our backtrail so we won't come back here again
 
360
            backtrail[(key, section.name)] = 1
 
361
 
 
362
            # Now start the actual work
 
363
            match = self._KEYCRE.search(value)
 
364
            while match:
 
365
                # The actual parsing of the match is implementation-dependent,
 
366
                # so delegate to our helper function
 
367
                k, v, s = self._parse_match(match)
 
368
                if k is None:
 
369
                    # That's the signal that no further interpolation is needed
 
370
                    replacement = v
 
371
                else:
 
372
                    # Further interpolation may be needed to obtain final value
 
373
                    replacement = recursive_interpolate(k, v, s, backtrail)
 
374
                # Replace the matched string with its final value
 
375
                start, end = match.span()
 
376
                value = ''.join((value[:start], replacement, value[end:]))
 
377
                new_search_start = start + len(replacement)
 
378
                # Pick up the next interpolation key, if any, for next time
 
379
                # through the while loop
 
380
                match = self._KEYCRE.search(value, new_search_start)
 
381
 
 
382
            # Now safe to come back here again; remove marker from backtrail
 
383
            del backtrail[(key, section.name)]
 
384
 
 
385
            return value
 
386
 
 
387
        # Back in interpolate(), all we have to do is kick off the recursive
 
388
        # function with appropriate starting values
 
389
        value = recursive_interpolate(key, value, self.section, {})
 
390
        return value
 
391
 
 
392
 
 
393
    def _fetch(self, key):
 
394
        """Helper function to fetch values from owning section.
 
395
 
 
396
        Returns a 2-tuple: the value, and the section where it was found.
 
397
        """
 
398
        # switch off interpolation before we try and fetch anything !
 
399
        save_interp = self.section.main.interpolation
 
400
        self.section.main.interpolation = False
 
401
 
 
402
        # Start at section that "owns" this InterpolationEngine
 
403
        current_section = self.section
 
404
        while True:
 
405
            # try the current section first
 
406
            val = current_section.get(key)
 
407
            if val is not None:
 
408
                break
 
409
            # try "DEFAULT" next
 
410
            val = current_section.get('DEFAULT', {}).get(key)
 
411
            if val is not None:
 
412
                break
 
413
            # move up to parent and try again
 
414
            # top-level's parent is itself
 
415
            if current_section.parent is current_section:
 
416
                # reached top level, time to give up
 
417
                break
 
418
            current_section = current_section.parent
 
419
 
 
420
        # restore interpolation to previous value before returning
 
421
        self.section.main.interpolation = save_interp
 
422
        if val is None:
 
423
            raise MissingInterpolationOption(key)
 
424
        return val, current_section
 
425
 
 
426
 
 
427
    def _parse_match(self, match):
 
428
        """Implementation-dependent helper function.
 
429
 
 
430
        Will be passed a match object corresponding to the interpolation
 
431
        key we just found (e.g., "%(foo)s" or "$foo"). Should look up that
 
432
        key in the appropriate config file section (using the ``_fetch()``
 
433
        helper function) and return a 3-tuple: (key, value, section)
 
434
 
 
435
        ``key`` is the name of the key we're looking for
 
436
        ``value`` is the value found for that key
 
437
        ``section`` is a reference to the section where it was found
 
438
 
 
439
        ``key`` and ``section`` should be None if no further
 
440
        interpolation should be performed on the resulting value
 
441
        (e.g., if we interpolated "$$" and returned "$").
 
442
        """
 
443
        raise NotImplementedError()
 
444
 
 
445
 
 
446
 
 
447
class ConfigParserInterpolation(InterpolationEngine):
 
448
    """Behaves like ConfigParser."""
 
449
    _KEYCRE = re.compile(r"%\(([^)]*)\)s")
 
450
 
 
451
    def _parse_match(self, match):
 
452
        key = match.group(1)
 
453
        value, section = self._fetch(key)
 
454
        return key, value, section
 
455
 
 
456
 
 
457
 
 
458
class TemplateInterpolation(InterpolationEngine):
 
459
    """Behaves like string.Template."""
 
460
    _delimiter = '$'
 
461
    _KEYCRE = re.compile(r"""
 
462
        \$(?:
 
463
          (?P<escaped>\$)              |   # Two $ signs
 
464
          (?P<named>[_a-z][_a-z0-9]*)  |   # $name format
 
465
          {(?P<braced>[^}]*)}              # ${name} format
 
466
        )
 
467
        """, re.IGNORECASE | re.VERBOSE)
 
468
 
 
469
    def _parse_match(self, match):
 
470
        # Valid name (in or out of braces): fetch value from section
 
471
        key = match.group('named') or match.group('braced')
 
472
        if key is not None:
 
473
            value, section = self._fetch(key)
 
474
            return key, value, section
 
475
        # Escaped delimiter (e.g., $$): return single delimiter
 
476
        if match.group('escaped') is not None:
 
477
            # Return None for key and section to indicate it's time to stop
 
478
            return None, self._delimiter, None
 
479
        # Anything else: ignore completely, just return it unchanged
 
480
        return None, match.group(), None
 
481
 
 
482
 
 
483
interpolation_engines = {
 
484
    'configparser': ConfigParserInterpolation,
 
485
    'template': TemplateInterpolation,
 
486
}
 
487
 
 
488
 
 
489
def __newobj__(cls, *args):
 
490
    # Hack for pickle
 
491
    return cls.__new__(cls, *args)
 
492
 
246
493
class Section(dict):
247
494
    """
248
495
    A dictionary-like object that represents a section in a config file.
249
 
    
250
 
    It does string interpolation if the 'interpolate' attribute
 
496
 
 
497
    It does string interpolation if the 'interpolation' attribute
251
498
    of the 'main' object is set to True.
252
 
    
253
 
    Interpolation is tried first from the 'DEFAULT' section of this object,
254
 
    next from the 'DEFAULT' section of the parent, lastly the main object.
255
 
    
 
499
 
 
500
    Interpolation is tried first from this object, then from the 'DEFAULT'
 
501
    section of this object, next from the parent and its 'DEFAULT' section,
 
502
    and so on until the main object is reached.
 
503
 
256
504
    A Section will behave like an ordered dictionary - following the
257
505
    order of the ``scalars`` and ``sections`` attributes.
258
506
    You can use this to change the order of members.
259
 
    
 
507
 
260
508
    Iteration follows the order: scalars, then sections.
261
509
    """
262
510
 
263
 
    _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
 
511
 
 
512
    def __setstate__(self, state):
 
513
        dict.update(self, state[0])
 
514
        self.__dict__.update(state[1])
 
515
 
 
516
    def __reduce__(self):
 
517
        state = (dict(self), self.__dict__)
 
518
        return (__newobj__, (self.__class__,), state)
 
519
 
264
520
 
265
521
    def __init__(self, parent, depth, main, indict=None, name=None):
266
522
        """
278
534
        self.main = main
279
535
        # level of nesting depth of this Section
280
536
        self.depth = depth
 
537
        # purely for information
 
538
        self.name = name
 
539
        #
 
540
        self._initialise()
 
541
        # we do this explicitly so that __setitem__ is used properly
 
542
        # (rather than just passing to ``dict.__init__``)
 
543
        for entry, value in indict.iteritems():
 
544
            self[entry] = value
 
545
 
 
546
 
 
547
    def _initialise(self):
281
548
        # the sequence of scalar values in this Section
282
549
        self.scalars = []
283
550
        # the sequence of sections in this Section
284
551
        self.sections = []
285
 
        # purely for information
286
 
        self.name = name
287
552
        # for comments :-)
288
553
        self.comments = {}
289
554
        self.inline_comments = {}
290
 
        # for the configspec
291
 
        self.configspec = {}
 
555
        # the configspec
 
556
        self.configspec = None
292
557
        # for defaults
293
558
        self.defaults = []
294
 
        #
295
 
        # we do this explicitly so that __setitem__ is used properly
296
 
        # (rather than just passing to ``dict.__init__``)
297
 
        for entry in indict:
298
 
            self[entry] = indict[entry]
299
 
 
300
 
    def _interpolate(self, value):
301
 
        """Nicked from ConfigParser."""
302
 
        depth = MAX_INTERPOL_DEPTH
303
 
        # loop through this until it's done
304
 
        while depth:
305
 
            depth -= 1
306
 
            if value.find("%(") != -1:
307
 
                value = self._KEYCRE.sub(self._interpolation_replace, value)
 
559
        self.default_values = {}
 
560
 
 
561
 
 
562
    def _interpolate(self, key, value):
 
563
        try:
 
564
            # do we already have an interpolation engine?
 
565
            engine = self._interpolation_engine
 
566
        except AttributeError:
 
567
            # not yet: first time running _interpolate(), so pick the engine
 
568
            name = self.main.interpolation
 
569
            if name == True:  # note that "if name:" would be incorrect here
 
570
                # backwards-compatibility: interpolation=True means use default
 
571
                name = DEFAULT_INTERPOLATION
 
572
            name = name.lower()  # so that "Template", "template", etc. all work
 
573
            class_ = interpolation_engines.get(name, None)
 
574
            if class_ is None:
 
575
                # invalid value for self.main.interpolation
 
576
                self.main.interpolation = False
 
577
                return value
308
578
            else:
309
 
                break
310
 
        else:
311
 
            raise InterpolationDepthError(value)
312
 
        return value
 
579
                # save reference to engine so we don't have to do this again
 
580
                engine = self._interpolation_engine = class_(self)
 
581
        # let the engine do the actual work
 
582
        return engine.interpolate(key, value)
313
583
 
314
 
    def _interpolation_replace(self, match):
315
 
        """ """
316
 
        s = match.group(1)
317
 
        if s is None:
318
 
            return match.group()
319
 
        else:
320
 
            # switch off interpolation before we try and fetch anything !
321
 
            self.main.interpolation = False
322
 
            # try the 'DEFAULT' member of *this section* first
323
 
            val = self.get('DEFAULT', {}).get(s)
324
 
            # try the 'DEFAULT' member of the *parent section* next
325
 
            if val is None:
326
 
                val = self.parent.get('DEFAULT', {}).get(s)
327
 
            # last, try the 'DEFAULT' member of the *main section*
328
 
            if val is None:
329
 
                val = self.main.get('DEFAULT', {}).get(s)
330
 
            self.main.interpolation = True
331
 
            if val is None:
332
 
                raise MissingInterpolationOption(s)
333
 
            return val
334
584
 
335
585
    def __getitem__(self, key):
336
586
        """Fetch the item and do string interpolation."""
337
587
        val = dict.__getitem__(self, key)
338
 
        if self.main.interpolation and isinstance(val, StringTypes):
339
 
            return self._interpolate(val)
 
588
        if self.main.interpolation and isinstance(val, basestring):
 
589
            return self._interpolate(key, val)
340
590
        return val
341
591
 
342
 
    def __setitem__(self, key, value):
 
592
 
 
593
    def __setitem__(self, key, value, unrepr=False):
343
594
        """
344
595
        Correctly set a value.
345
 
        
 
596
 
346
597
        Making dictionary values Section instances.
347
598
        (We have to special case 'Section' instances - which are also dicts)
348
 
        
 
599
 
349
600
        Keys must be strings.
350
601
        Values need only be strings (or lists of strings) if
351
602
        ``main.stringify`` is set.
 
603
 
 
604
        ``unrepr`` must be set when setting a value to a dictionary, without
 
605
        creating a new sub-section.
352
606
        """
353
 
        if not isinstance(key, StringTypes):
354
 
            raise ValueError, 'The key "%s" is not a string.' % key
 
607
        if not isinstance(key, basestring):
 
608
            raise ValueError('The key "%s" is not a string.' % key)
 
609
 
355
610
        # add the comment
356
611
        if key not in self.comments:
357
612
            self.comments[key] = []
364
619
            if key not in self:
365
620
                self.sections.append(key)
366
621
            dict.__setitem__(self, key, value)
367
 
        elif isinstance(value, dict):
 
622
        elif isinstance(value, dict) and not unrepr:
368
623
            # First create the new depth level,
369
624
            # then create the section
370
625
            if key not in self:
383
638
            if key not in self:
384
639
                self.scalars.append(key)
385
640
            if not self.main.stringify:
386
 
                if isinstance(value, StringTypes):
 
641
                if isinstance(value, basestring):
387
642
                    pass
388
643
                elif isinstance(value, (list, tuple)):
389
644
                    for entry in value:
390
 
                        if not isinstance(entry, StringTypes):
391
 
                            raise TypeError, (
392
 
                                'Value is not a string "%s".' % entry)
 
645
                        if not isinstance(entry, basestring):
 
646
                            raise TypeError('Value is not a string "%s".' % entry)
393
647
                else:
394
 
                    raise TypeError, 'Value is not a string "%s".' % value
 
648
                    raise TypeError('Value is not a string "%s".' % value)
395
649
            dict.__setitem__(self, key, value)
396
650
 
 
651
 
397
652
    def __delitem__(self, key):
398
653
        """Remove items from the sequence when deleting."""
399
654
        dict. __delitem__(self, key)
404
659
        del self.comments[key]
405
660
        del self.inline_comments[key]
406
661
 
 
662
 
407
663
    def get(self, key, default=None):
408
664
        """A version of ``get`` that doesn't bypass string interpolation."""
409
665
        try:
411
667
        except KeyError:
412
668
            return default
413
669
 
 
670
 
414
671
    def update(self, indict):
415
672
        """
416
673
        A version of update that uses our ``__setitem__``.
420
677
 
421
678
 
422
679
    def pop(self, key, *args):
423
 
        """ """
 
680
        """
 
681
        'D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
 
682
        If key is not found, d is returned if given, otherwise KeyError is raised'
 
683
        """
424
684
        val = dict.pop(self, key, *args)
425
685
        if key in self.scalars:
426
686
            del self.comments[key]
430
690
            del self.comments[key]
431
691
            del self.inline_comments[key]
432
692
            self.sections.remove(key)
433
 
        if self.main.interpolation and isinstance(val, StringTypes):
434
 
            return self._interpolate(val)
 
693
        if self.main.interpolation and isinstance(val, basestring):
 
694
            return self._interpolate(key, val)
435
695
        return val
436
696
 
 
697
 
437
698
    def popitem(self):
438
699
        """Pops the first (key,val)"""
439
700
        sequence = (self.scalars + self.sections)
440
701
        if not sequence:
441
 
            raise KeyError, ": 'popitem(): dictionary is empty'"
 
702
            raise KeyError(": 'popitem(): dictionary is empty'")
442
703
        key = sequence[0]
443
704
        val =  self[key]
444
705
        del self[key]
445
706
        return key, val
446
707
 
 
708
 
447
709
    def clear(self):
448
710
        """
449
711
        A version of clear that also affects scalars/sections
450
712
        Also clears comments and configspec.
451
 
        
 
713
 
452
714
        Leaves other attributes alone :
453
715
            depth/main/parent are not affected
454
716
        """
457
719
        self.sections = []
458
720
        self.comments = {}
459
721
        self.inline_comments = {}
460
 
        self.configspec = {}
 
722
        self.configspec = None
 
723
 
461
724
 
462
725
    def setdefault(self, key, default=None):
463
726
        """A version of setdefault that sets sequence if appropriate."""
467
730
            self[key] = default
468
731
            return self[key]
469
732
 
 
733
 
470
734
    def items(self):
471
 
        """ """
 
735
        """D.items() -> list of D's (key, value) pairs, as 2-tuples"""
472
736
        return zip((self.scalars + self.sections), self.values())
473
737
 
 
738
 
474
739
    def keys(self):
475
 
        """ """
 
740
        """D.keys() -> list of D's keys"""
476
741
        return (self.scalars + self.sections)
477
742
 
 
743
 
478
744
    def values(self):
479
 
        """ """
 
745
        """D.values() -> list of D's values"""
480
746
        return [self[key] for key in (self.scalars + self.sections)]
481
747
 
 
748
 
482
749
    def iteritems(self):
483
 
        """ """
 
750
        """D.iteritems() -> an iterator over the (key, value) items of D"""
484
751
        return iter(self.items())
485
752
 
 
753
 
486
754
    def iterkeys(self):
487
 
        """ """
 
755
        """D.iterkeys() -> an iterator over the keys of D"""
488
756
        return iter((self.scalars + self.sections))
489
757
 
490
758
    __iter__ = iterkeys
491
759
 
 
760
 
492
761
    def itervalues(self):
493
 
        """ """
 
762
        """D.itervalues() -> an iterator over the values of D"""
494
763
        return iter(self.values())
495
764
 
 
765
 
496
766
    def __repr__(self):
 
767
        """x.__repr__() <==> repr(x)"""
497
768
        return '{%s}' % ', '.join([('%s: %s' % (repr(key), repr(self[key])))
498
769
            for key in (self.scalars + self.sections)])
499
770
 
500
771
    __str__ = __repr__
 
772
    __str__.__doc__ = "x.__str__() <==> str(x)"
 
773
 
501
774
 
502
775
    # Extra methods - not in a normal dictionary
503
776
 
504
777
    def dict(self):
505
778
        """
506
779
        Return a deepcopy of self as a dictionary.
507
 
        
 
780
 
508
781
        All members that are ``Section`` instances are recursively turned to
509
782
        ordinary dictionaries - by calling their ``dict`` method.
510
 
        
 
783
 
511
784
        >>> n = a.dict()
512
785
        >>> n == a
513
786
        1
519
792
            this_entry = self[entry]
520
793
            if isinstance(this_entry, Section):
521
794
                this_entry = this_entry.dict()
522
 
            elif isinstance(this_entry, (list, tuple)):
 
795
            elif isinstance(this_entry, list):
523
796
                # create a copy rather than a reference
524
797
                this_entry = list(this_entry)
 
798
            elif isinstance(this_entry, tuple):
 
799
                # create a copy rather than a reference
 
800
                this_entry = tuple(this_entry)
525
801
            newdict[entry] = this_entry
526
802
        return newdict
527
803
 
 
804
 
528
805
    def merge(self, indict):
529
806
        """
530
807
        A recursive update - useful for merging config files.
531
 
        
 
808
 
532
809
        >>> a = '''[section1]
533
810
        ...     option1 = True
534
811
        ...     [[subsection]]
542
819
        >>> c2 = ConfigObj(a)
543
820
        >>> c2.merge(c1)
544
821
        >>> c2
545
 
        {'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}}
 
822
        ConfigObj({'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}})
546
823
        """
547
824
        for key, val in indict.items():
548
825
            if (key in self and isinstance(self[key], dict) and
549
826
                                isinstance(val, dict)):
550
827
                self[key].merge(val)
551
 
            else:   
 
828
            else:
552
829
                self[key] = val
553
830
 
 
831
 
554
832
    def rename(self, oldkey, newkey):
555
833
        """
556
834
        Change a keyname to another, without changing position in sequence.
557
 
        
 
835
 
558
836
        Implemented so that transformations can be made on keys,
559
837
        as well as on values. (used by encode and decode)
560
 
        
 
838
 
561
839
        Also renames comments.
562
840
        """
563
841
        if oldkey in self.scalars:
565
843
        elif oldkey in self.sections:
566
844
            the_list = self.sections
567
845
        else:
568
 
            raise KeyError, 'Key "%s" not found.' % oldkey
 
846
            raise KeyError('Key "%s" not found.' % oldkey)
569
847
        pos = the_list.index(oldkey)
570
848
        #
571
849
        val = self[oldkey]
580
858
        self.comments[newkey] = comm
581
859
        self.inline_comments[newkey] = inline_comment
582
860
 
 
861
 
583
862
    def walk(self, function, raise_errors=True,
584
863
            call_on_sections=False, **keywargs):
585
864
        """
586
865
        Walk every member and call a function on the keyword and value.
587
 
        
 
866
 
588
867
        Return a dictionary of the return values
589
 
        
 
868
 
590
869
        If the function raises an exception, raise the errror
591
870
        unless ``raise_errors=False``, in which case set the return value to
592
871
        ``False``.
593
 
        
 
872
 
594
873
        Any unrecognised keyword arguments you pass to walk, will be pased on
595
874
        to the function you pass in.
596
 
        
 
875
 
597
876
        Note: if ``call_on_sections`` is ``True`` then - on encountering a
598
877
        subsection, *first* the function is called for the *whole* subsection,
599
878
        and then recurses into it's members. This means your function must be
600
879
        able to handle strings, dictionaries and lists. This allows you
601
880
        to change the key of subsections as well as for ordinary members. The
602
881
        return value when called on the whole subsection has to be discarded.
603
 
        
 
882
 
604
883
        See  the encode and decode methods for examples, including functions.
605
 
        
606
 
        .. caution::
607
 
        
 
884
 
 
885
        .. admonition:: caution
 
886
 
608
887
            You can use ``walk`` to transform the names of members of a section
609
888
            but you mustn't add or delete members.
610
 
        
 
889
 
611
890
        >>> config = '''[XXXXsection]
612
891
        ... XXXXkey = XXXXvalue'''.splitlines()
613
892
        >>> cfg = ConfigObj(config)
614
893
        >>> cfg
615
 
        {'XXXXsection': {'XXXXkey': 'XXXXvalue'}}
 
894
        ConfigObj({'XXXXsection': {'XXXXkey': 'XXXXvalue'}})
616
895
        >>> def transform(section, key):
617
896
        ...     val = section[key]
618
897
        ...     newkey = key.replace('XXXX', 'CLIENT1')
625
904
        >>> cfg.walk(transform, call_on_sections=True)
626
905
        {'CLIENT1section': {'CLIENT1key': None}}
627
906
        >>> cfg
628
 
        {'CLIENT1section': {'CLIENT1key': 'CLIENT1value'}}
 
907
        ConfigObj({'CLIENT1section': {'CLIENT1key': 'CLIENT1value'}})
629
908
        """
630
909
        out = {}
631
910
        # scalars first
664
943
                **keywargs)
665
944
        return out
666
945
 
667
 
    def decode(self, encoding):
668
 
        """
669
 
        Decode all strings and values to unicode, using the specified encoding.
670
 
        
671
 
        Works with subsections and list values.
672
 
        
673
 
        Uses the ``walk`` method.
674
 
        
675
 
        Testing ``encode`` and ``decode``.
676
 
        >>> m = ConfigObj(a)
677
 
        >>> m.decode('ascii')
678
 
        >>> def testuni(val):
679
 
        ...     for entry in val:
680
 
        ...         if not isinstance(entry, unicode):
681
 
        ...             print >> sys.stderr, type(entry)
682
 
        ...             raise AssertionError, 'decode failed.'
683
 
        ...         if isinstance(val[entry], dict):
684
 
        ...             testuni(val[entry])
685
 
        ...         elif not isinstance(val[entry], unicode):
686
 
        ...             raise AssertionError, 'decode failed.'
687
 
        >>> testuni(m)
688
 
        >>> m.encode('ascii')
689
 
        >>> a == m
690
 
        1
691
 
        """
692
 
        def decode(section, key, encoding=encoding):
693
 
            """ """
694
 
            val = section[key]
695
 
            if isinstance(val, (list, tuple)):
696
 
                newval = []
697
 
                for entry in val:
698
 
                    newval.append(entry.decode(encoding))
699
 
            elif isinstance(val, dict):
700
 
                newval = val
701
 
            else:
702
 
                newval = val.decode(encoding)
703
 
            newkey = key.decode(encoding)
704
 
            section.rename(key, newkey)
705
 
            section[newkey] = newval
706
 
        # using ``call_on_sections`` allows us to modify section names
707
 
        self.walk(decode, call_on_sections=True)
708
 
 
709
 
    def encode(self, encoding):
710
 
        """
711
 
        Encode all strings and values from unicode,
712
 
        using the specified encoding.
713
 
        
714
 
        Works with subsections and list values.
715
 
        Uses the ``walk`` method.
716
 
        """
717
 
        def encode(section, key, encoding=encoding):
718
 
            """ """
719
 
            val = section[key]
720
 
            if isinstance(val, (list, tuple)):
721
 
                newval = []
722
 
                for entry in val:
723
 
                    newval.append(entry.encode(encoding))
724
 
            elif isinstance(val, dict):
725
 
                newval = val
726
 
            else:
727
 
                newval = val.encode(encoding)
728
 
            newkey = key.encode(encoding)
729
 
            section.rename(key, newkey)
730
 
            section[newkey] = newval
731
 
        self.walk(encode, call_on_sections=True)
732
 
 
733
 
    def istrue(self, key):
734
 
        """A deprecated version of ``as_bool``."""
735
 
        warn('use of ``istrue`` is deprecated. Use ``as_bool`` method '
736
 
                'instead.', DeprecationWarning)
737
 
        return self.as_bool(key)
738
946
 
739
947
    def as_bool(self, key):
740
948
        """
741
949
        Accepts a key as input. The corresponding value must be a string or
742
950
        the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to
743
951
        retain compatibility with Python 2.2.
744
 
        
745
 
        If the string is one of  ``True``, ``On``, ``Yes``, or ``1`` it returns 
 
952
 
 
953
        If the string is one of  ``True``, ``On``, ``Yes``, or ``1`` it returns
746
954
        ``True``.
747
 
        
748
 
        If the string is one of  ``False``, ``Off``, ``No``, or ``0`` it returns 
 
955
 
 
956
        If the string is one of  ``False``, ``Off``, ``No``, or ``0`` it returns
749
957
        ``False``.
750
 
        
 
958
 
751
959
        ``as_bool`` is not case sensitive.
752
 
        
 
960
 
753
961
        Any other input will raise a ``ValueError``.
754
 
        
 
962
 
755
963
        >>> a = ConfigObj()
756
964
        >>> a['a'] = 'fish'
757
965
        >>> a.as_bool('a')
771
979
            return False
772
980
        else:
773
981
            try:
774
 
                if not isinstance(val, StringTypes):
775
 
                    raise KeyError
 
982
                if not isinstance(val, basestring):
 
983
                    # TODO: Why do we raise a KeyError here?
 
984
                    raise KeyError()
776
985
                else:
777
986
                    return self.main._bools[val.lower()]
778
987
            except KeyError:
779
988
                raise ValueError('Value "%s" is neither True nor False' % val)
780
989
 
 
990
 
781
991
    def as_int(self, key):
782
992
        """
783
993
        A convenience method which coerces the specified value to an integer.
784
 
        
 
994
 
785
995
        If the value is an invalid literal for ``int``, a ``ValueError`` will
786
996
        be raised.
787
 
        
 
997
 
788
998
        >>> a = ConfigObj()
789
999
        >>> a['a'] = 'fish'
790
1000
        >>> a.as_int('a')
791
1001
        Traceback (most recent call last):
792
 
        ValueError: invalid literal for int(): fish
 
1002
        ValueError: invalid literal for int() with base 10: 'fish'
793
1003
        >>> a['b'] = '1'
794
1004
        >>> a.as_int('b')
795
1005
        1
796
1006
        >>> a['b'] = '3.2'
797
1007
        >>> a.as_int('b')
798
1008
        Traceback (most recent call last):
799
 
        ValueError: invalid literal for int(): 3.2
 
1009
        ValueError: invalid literal for int() with base 10: '3.2'
800
1010
        """
801
1011
        return int(self[key])
802
1012
 
 
1013
 
803
1014
    def as_float(self, key):
804
1015
        """
805
1016
        A convenience method which coerces the specified value to a float.
806
 
        
 
1017
 
807
1018
        If the value is an invalid literal for ``float``, a ``ValueError`` will
808
1019
        be raised.
809
 
        
 
1020
 
810
1021
        >>> a = ConfigObj()
811
1022
        >>> a['a'] = 'fish'
812
1023
        >>> a.as_float('a')
820
1031
        3.2000000000000002
821
1032
        """
822
1033
        return float(self[key])
823
 
    
 
1034
 
 
1035
 
 
1036
    def as_list(self, key):
 
1037
        """
 
1038
        A convenience method which fetches the specified value, guaranteeing
 
1039
        that it is a list.
 
1040
 
 
1041
        >>> a = ConfigObj()
 
1042
        >>> a['a'] = 1
 
1043
        >>> a.as_list('a')
 
1044
        [1]
 
1045
        >>> a['a'] = (1,)
 
1046
        >>> a.as_list('a')
 
1047
        [1]
 
1048
        >>> a['a'] = [1]
 
1049
        >>> a.as_list('a')
 
1050
        [1]
 
1051
        """
 
1052
        result = self[key]
 
1053
        if isinstance(result, (tuple, list)):
 
1054
            return list(result)
 
1055
        return [result]
 
1056
 
 
1057
 
 
1058
    def restore_default(self, key):
 
1059
        """
 
1060
        Restore (and return) default value for the specified key.
 
1061
 
 
1062
        This method will only work for a ConfigObj that was created
 
1063
        with a configspec and has been validated.
 
1064
 
 
1065
        If there is no default value for this key, ``KeyError`` is raised.
 
1066
        """
 
1067
        default = self.default_values[key]
 
1068
        dict.__setitem__(self, key, default)
 
1069
        if key not in self.defaults:
 
1070
            self.defaults.append(key)
 
1071
        return default
 
1072
 
 
1073
 
 
1074
    def restore_defaults(self):
 
1075
        """
 
1076
        Recursively restore default values to all members
 
1077
        that have them.
 
1078
 
 
1079
        This method will only work for a ConfigObj that was created
 
1080
        with a configspec and has been validated.
 
1081
 
 
1082
        It doesn't delete or modify entries without default values.
 
1083
        """
 
1084
        for key in self.default_values:
 
1085
            self.restore_default(key)
 
1086
 
 
1087
        for section in self.sections:
 
1088
            self[section].restore_defaults()
 
1089
 
824
1090
 
825
1091
class ConfigObj(Section):
826
 
    """
827
 
    An object to read, create, and write config files.
828
 
    
829
 
    Testing with duplicate keys and sections.
830
 
    
831
 
    >>> c = '''
832
 
    ... [hello]
833
 
    ... member = value
834
 
    ... [hello again]
835
 
    ... member = value
836
 
    ... [ "hello" ]
837
 
    ... member = value
838
 
    ... '''
839
 
    >>> ConfigObj(c.split('\\n'), raise_errors = True)
840
 
    Traceback (most recent call last):
841
 
    DuplicateError: Duplicate section name at line 5.
842
 
    
843
 
    >>> d = '''
844
 
    ... [hello]
845
 
    ... member = value
846
 
    ... [hello again]
847
 
    ... member1 = value
848
 
    ... member2 = value
849
 
    ... 'member1' = value
850
 
    ... [ "and again" ]
851
 
    ... member = value
852
 
    ... '''
853
 
    >>> ConfigObj(d.split('\\n'), raise_errors = True)
854
 
    Traceback (most recent call last):
855
 
    DuplicateError: Duplicate keyword name at line 6.
856
 
    """
 
1092
    """An object to read, create, and write config files."""
857
1093
 
858
1094
    _keyword = re.compile(r'''^ # line start
859
1095
        (\s*)                   # indentation
883
1119
 
884
1120
    # this regexp pulls list values out as a single string
885
1121
    # or single values and comments
 
1122
    # FIXME: this regex adds a '' to the end of comma terminated lists
 
1123
    #   workaround in ``_handle_value``
886
1124
    _valueexp = re.compile(r'''^
887
1125
        (?:
888
1126
            (?:
891
1129
                        (?:
892
1130
                            (?:".*?")|              # double quotes
893
1131
                            (?:'.*?')|              # single quotes
894
 
                            (?:[^'",\#][^,\#]*?)       # unquoted
 
1132
                            (?:[^'",\#][^,\#]*?)    # unquoted
895
1133
                        )
896
1134
                        \s*,\s*                     # comma
897
1135
                    )*      # match all list items ending in a comma (if any)
899
1137
                (
900
1138
                    (?:".*?")|                      # double quotes
901
1139
                    (?:'.*?')|                      # single quotes
902
 
                    (?:[^'",\#\s][^,]*?)             # unquoted
 
1140
                    (?:[^'",\#\s][^,]*?)|           # unquoted
 
1141
                    (?:(?<!,))                      # Empty value
903
1142
                )?          # last item in a list - or string value
904
1143
            )|
905
1144
            (,)             # alternatively a single comma - empty list
925
1164
        (
926
1165
            (?:".*?")|          # double quotes
927
1166
            (?:'.*?')|          # single quotes
928
 
            (?:[^'"\#].*?)      # unquoted
 
1167
            (?:[^'"\#].*?)|     # unquoted
 
1168
            (?:)                # Empty value
929
1169
        )
930
1170
        \s*(\#.*)?              # optional comment
931
1171
        $''',
950
1190
        'true': True, 'false': False,
951
1191
        }
952
1192
 
953
 
    def __init__(self, infile=None, options=None, **kwargs):
 
1193
 
 
1194
    def __init__(self, infile=None, options=None, _inspec=False, **kwargs):
954
1195
        """
955
 
        Parse or create a config file object.
956
 
        
 
1196
        Parse a config file or create a config file object.
 
1197
 
957
1198
        ``ConfigObj(infile=None, options=None, **kwargs)``
958
1199
        """
959
 
        if infile is None:
960
 
            infile = []
961
 
        if options is None:
962
 
            options = {}
 
1200
        self._inspec = _inspec
 
1201
        # init the superclass
 
1202
        Section.__init__(self, self, 0, self)
 
1203
 
 
1204
        infile = infile or []
 
1205
        options = dict(options or {})
 
1206
 
963
1207
        # keyword arguments take precedence over an options dictionary
964
1208
        options.update(kwargs)
965
 
        # init the superclass
966
 
        Section.__init__(self, self, 0, self)
967
 
        #
 
1209
        if _inspec:
 
1210
            options['list_values'] = False
 
1211
 
968
1212
        defaults = OPTION_DEFAULTS.copy()
969
 
        for entry in options.keys():
970
 
            if entry not in defaults.keys():
971
 
                raise TypeError, 'Unrecognised option "%s".' % entry
972
1213
        # TODO: check the values too.
973
 
        #
 
1214
        for entry in options:
 
1215
            if entry not in defaults:
 
1216
                raise TypeError('Unrecognised option "%s".' % entry)
 
1217
 
974
1218
        # Add any explicit options to the defaults
975
1219
        defaults.update(options)
976
 
        #
977
 
        # initialise a few variables
978
 
        self.filename = None
979
 
        self._errors = []
980
 
        self.raise_errors = defaults['raise_errors']
981
 
        self.interpolation = defaults['interpolation']
982
 
        self.list_values = defaults['list_values']
983
 
        self.create_empty = defaults['create_empty']
984
 
        self.file_error = defaults['file_error']
985
 
        self.stringify = defaults['stringify']
986
 
        self.indent_type = defaults['indent_type']
987
 
        self.encoding = defaults['encoding']
988
 
        self.default_encoding = defaults['default_encoding']
989
 
        self.BOM = False
990
 
        self.newlines = None
991
 
        #
992
 
        self.initial_comment = []
993
 
        self.final_comment = []
994
 
        #
995
 
        if isinstance(infile, StringTypes):
 
1220
        self._initialise(defaults)
 
1221
        configspec = defaults['configspec']
 
1222
        self._original_configspec = configspec
 
1223
        self._load(infile, configspec)
 
1224
 
 
1225
 
 
1226
    def _load(self, infile, configspec):
 
1227
        if isinstance(infile, basestring):
996
1228
            self.filename = infile
997
1229
            if os.path.isfile(infile):
998
 
                infile = open(infile).read() or []
 
1230
                h = open(infile, 'rb')
 
1231
                infile = h.read() or []
 
1232
                h.close()
999
1233
            elif self.file_error:
1000
1234
                # raise an error if the file doesn't exist
1001
 
                raise IOError, 'Config file not found: "%s".' % self.filename
 
1235
                raise IOError('Config file not found: "%s".' % self.filename)
1002
1236
            else:
1003
1237
                # file doesn't already exist
1004
1238
                if self.create_empty:
1005
1239
                    # this is a good test that the filename specified
1006
 
                    # isn't impossible - like on a non existent device
 
1240
                    # isn't impossible - like on a non-existent device
1007
1241
                    h = open(infile, 'w')
1008
1242
                    h.write('')
1009
1243
                    h.close()
1010
1244
                infile = []
 
1245
 
1011
1246
        elif isinstance(infile, (list, tuple)):
1012
1247
            infile = list(infile)
 
1248
 
1013
1249
        elif isinstance(infile, dict):
1014
1250
            # initialise self
1015
1251
            # the Section class handles creating subsections
1016
1252
            if isinstance(infile, ConfigObj):
1017
1253
                # get a copy of our ConfigObj
1018
1254
                infile = infile.dict()
 
1255
 
1019
1256
            for entry in infile:
1020
1257
                self[entry] = infile[entry]
1021
1258
            del self._errors
1022
 
            if defaults['configspec'] is not None:
1023
 
                self._handle_configspec(defaults['configspec'])
 
1259
 
 
1260
            if configspec is not None:
 
1261
                self._handle_configspec(configspec)
1024
1262
            else:
1025
1263
                self.configspec = None
1026
1264
            return
1027
 
        elif getattr(infile, 'read', None) is not None:
 
1265
 
 
1266
        elif getattr(infile, 'read', MISSING) is not MISSING:
1028
1267
            # This supports file like objects
1029
1268
            infile = infile.read() or []
1030
1269
            # needs splitting into lines - but needs doing *after* decoding
1031
1270
            # in case it's not an 8 bit encoding
1032
1271
        else:
1033
 
            raise TypeError, ('infile must be a filename,'
1034
 
                ' file like object, or list of lines.')
1035
 
        #
 
1272
            raise TypeError('infile must be a filename, file like object, or list of lines.')
 
1273
 
1036
1274
        if infile:
1037
1275
            # don't do it for the empty ConfigObj
1038
1276
            infile = self._handle_bom(infile)
1041
1279
            # Set the newlines attribute (first line ending it finds)
1042
1280
            # and strip trailing '\n' or '\r' from lines
1043
1281
            for line in infile:
1044
 
                if (not line) or (line[-1] not in '\r\n'):
 
1282
                if (not line) or (line[-1] not in ('\r', '\n', '\r\n')):
1045
1283
                    continue
1046
1284
                for end in ('\r\n', '\n', '\r'):
1047
1285
                    if line.endswith(end):
1048
1286
                        self.newlines = end
1049
1287
                        break
1050
1288
                break
 
1289
 
1051
1290
            infile = [line.rstrip('\r\n') for line in infile]
1052
 
        #
 
1291
 
1053
1292
        self._parse(infile)
1054
1293
        # if we had any errors, now is the time to raise them
1055
1294
        if self._errors:
1056
 
            error = ConfigObjError("Parsing failed.")
 
1295
            info = "at line %s." % self._errors[0].line_number
 
1296
            if len(self._errors) > 1:
 
1297
                msg = "Parsing failed with several errors.\nFirst error %s" % info
 
1298
                error = ConfigObjError(msg)
 
1299
            else:
 
1300
                error = self._errors[0]
1057
1301
            # set the errors attribute; it's a list of tuples:
1058
1302
            # (error_type, message, line_number)
1059
1303
            error.errors = self._errors
1062
1306
            raise error
1063
1307
        # delete private attributes
1064
1308
        del self._errors
1065
 
        #
1066
 
        if defaults['configspec'] is None:
 
1309
 
 
1310
        if configspec is None:
1067
1311
            self.configspec = None
1068
1312
        else:
1069
 
            self._handle_configspec(defaults['configspec'])
 
1313
            self._handle_configspec(configspec)
 
1314
 
 
1315
 
 
1316
    def _initialise(self, options=None):
 
1317
        if options is None:
 
1318
            options = OPTION_DEFAULTS
 
1319
 
 
1320
        # initialise a few variables
 
1321
        self.filename = None
 
1322
        self._errors = []
 
1323
        self.raise_errors = options['raise_errors']
 
1324
        self.interpolation = options['interpolation']
 
1325
        self.list_values = options['list_values']
 
1326
        self.create_empty = options['create_empty']
 
1327
        self.file_error = options['file_error']
 
1328
        self.stringify = options['stringify']
 
1329
        self.indent_type = options['indent_type']
 
1330
        self.encoding = options['encoding']
 
1331
        self.default_encoding = options['default_encoding']
 
1332
        self.BOM = False
 
1333
        self.newlines = None
 
1334
        self.write_empty_values = options['write_empty_values']
 
1335
        self.unrepr = options['unrepr']
 
1336
 
 
1337
        self.initial_comment = []
 
1338
        self.final_comment = []
 
1339
        self.configspec = None
 
1340
 
 
1341
        if self._inspec:
 
1342
            self.list_values = False
 
1343
 
 
1344
        # Clear section attributes as well
 
1345
        Section._initialise(self)
 
1346
 
 
1347
 
 
1348
    def __repr__(self):
 
1349
        return ('ConfigObj({%s})' %
 
1350
                ', '.join([('%s: %s' % (repr(key), repr(self[key])))
 
1351
                for key in (self.scalars + self.sections)]))
 
1352
 
1070
1353
 
1071
1354
    def _handle_bom(self, infile):
1072
1355
        """
1073
1356
        Handle any BOM, and decode if necessary.
1074
 
        
 
1357
 
1075
1358
        If an encoding is specified, that *must* be used - but the BOM should
1076
1359
        still be removed (and the BOM attribute set).
1077
 
        
 
1360
 
1078
1361
        (If the encoding is wrongly specified, then a BOM for an alternative
1079
1362
        encoding won't be discovered or removed.)
1080
 
        
 
1363
 
1081
1364
        If an encoding is not specified, UTF8 or UTF16 BOM will be detected and
1082
1365
        removed. The BOM attribute will be set. UTF16 will be decoded to
1083
1366
        unicode.
1084
 
        
 
1367
 
1085
1368
        NOTE: This method must not be called with an empty ``infile``.
1086
 
        
 
1369
 
1087
1370
        Specifying the *wrong* encoding is likely to cause a
1088
1371
        ``UnicodeDecodeError``.
1089
 
        
 
1372
 
1090
1373
        ``infile`` must always be returned as a list of lines, but may be
1091
1374
        passed in as a single string.
1092
1375
        """
1093
1376
        if ((self.encoding is not None) and
1094
1377
            (self.encoding.lower() not in BOM_LIST)):
1095
1378
            # No need to check for a BOM
1096
 
            # encoding specified doesn't have one
 
1379
            # the encoding specified doesn't have one
1097
1380
            # just decode
1098
1381
            return self._decode(infile, self.encoding)
1099
 
        #
 
1382
 
1100
1383
        if isinstance(infile, (list, tuple)):
1101
1384
            line = infile[0]
1102
1385
        else:
1118
1401
                        ##self.BOM = True
1119
1402
                        # Don't need to remove BOM
1120
1403
                        return self._decode(infile, encoding)
1121
 
                #
 
1404
 
1122
1405
                # If we get this far, will *probably* raise a DecodeError
1123
1406
                # As it doesn't appear to start with a BOM
1124
1407
                return self._decode(infile, self.encoding)
1125
 
            #
 
1408
 
1126
1409
            # Must be UTF8
1127
1410
            BOM = BOM_SET[enc]
1128
1411
            if not line.startswith(BOM):
1129
1412
                return self._decode(infile, self.encoding)
1130
 
            #
 
1413
 
1131
1414
            newline = line[len(BOM):]
1132
 
            #
 
1415
 
1133
1416
            # BOM removed
1134
1417
            if isinstance(infile, (list, tuple)):
1135
1418
                infile[0] = newline
1137
1420
                infile = newline
1138
1421
            self.BOM = True
1139
1422
            return self._decode(infile, self.encoding)
1140
 
        #
 
1423
 
1141
1424
        # No encoding specified - so we need to check for UTF8/UTF16
1142
1425
        for BOM, (encoding, final_encoding) in BOMS.items():
1143
1426
            if not line.startswith(BOM):
1155
1438
                    else:
1156
1439
                        infile = newline
1157
1440
                    # UTF8 - don't decode
1158
 
                    if isinstance(infile, StringTypes):
 
1441
                    if isinstance(infile, basestring):
1159
1442
                        return infile.splitlines(True)
1160
1443
                    else:
1161
1444
                        return infile
1162
1445
                # UTF16 - have to decode
1163
1446
                return self._decode(infile, encoding)
1164
 
        #
 
1447
 
1165
1448
        # No BOM discovered and no encoding specified, just return
1166
 
        if isinstance(infile, StringTypes):
 
1449
        if isinstance(infile, basestring):
1167
1450
            # infile read from a file will be a single string
1168
1451
            return infile.splitlines(True)
1169
 
        else:
1170
 
            return infile
1171
 
 
1172
 
    def _a_to_u(self, string):
1173
 
        """Decode ascii strings to unicode if a self.encoding is specified."""
1174
 
        if not self.encoding:
1175
 
            return string
1176
 
        else:
1177
 
            return string.decode('ascii')
 
1452
        return infile
 
1453
 
 
1454
 
 
1455
    def _a_to_u(self, aString):
 
1456
        """Decode ASCII strings to unicode if a self.encoding is specified."""
 
1457
        if self.encoding:
 
1458
            return aString.decode('ascii')
 
1459
        else:
 
1460
            return aString
 
1461
 
1178
1462
 
1179
1463
    def _decode(self, infile, encoding):
1180
1464
        """
1181
1465
        Decode infile to unicode. Using the specified encoding.
1182
 
        
 
1466
 
1183
1467
        if is a string, it also needs converting to a list.
1184
1468
        """
1185
 
        if isinstance(infile, StringTypes):
 
1469
        if isinstance(infile, basestring):
1186
1470
            # can't be unicode
1187
1471
            # NOTE: Could raise a ``UnicodeDecodeError``
1188
1472
            return infile.decode(encoding).splitlines(True)
1194
1478
                infile[i] = line.decode(encoding)
1195
1479
        return infile
1196
1480
 
 
1481
 
1197
1482
    def _decode_element(self, line):
1198
1483
        """Decode element to unicode if necessary."""
1199
1484
        if not self.encoding:
1202
1487
            return line.decode(self.default_encoding)
1203
1488
        return line
1204
1489
 
 
1490
 
1205
1491
    def _str(self, value):
1206
1492
        """
1207
1493
        Used by ``stringify`` within validate, to turn non-string values
1208
1494
        into strings.
1209
1495
        """
1210
 
        if not isinstance(value, StringTypes):
 
1496
        if not isinstance(value, basestring):
1211
1497
            return str(value)
1212
1498
        else:
1213
1499
            return value
1214
1500
 
 
1501
 
1215
1502
    def _parse(self, infile):
1216
 
        """
1217
 
        Actually parse the config file
1218
 
        
1219
 
        Testing Interpolation
1220
 
        
1221
 
        >>> c = ConfigObj()
1222
 
        >>> c['DEFAULT'] = {
1223
 
        ...     'b': 'goodbye',
1224
 
        ...     'userdir': 'c:\\\\home',
1225
 
        ...     'c': '%(d)s',
1226
 
        ...     'd': '%(c)s'
1227
 
        ... }
1228
 
        >>> c['section'] = {
1229
 
        ...     'a': '%(datadir)s\\\\some path\\\\file.py',
1230
 
        ...     'b': '%(userdir)s\\\\some path\\\\file.py',
1231
 
        ...     'c': 'Yo %(a)s',
1232
 
        ...     'd': '%(not_here)s',
1233
 
        ...     'e': '%(c)s',
1234
 
        ... }
1235
 
        >>> c['section']['DEFAULT'] = {
1236
 
        ...     'datadir': 'c:\\\\silly_test',
1237
 
        ...     'a': 'hello - %(b)s',
1238
 
        ... }
1239
 
        >>> c['section']['a'] == 'c:\\\\silly_test\\\\some path\\\\file.py'
1240
 
        1
1241
 
        >>> c['section']['b'] == 'c:\\\\home\\\\some path\\\\file.py'
1242
 
        1
1243
 
        >>> c['section']['c'] == 'Yo hello - goodbye'
1244
 
        1
1245
 
        
1246
 
        Switching Interpolation Off
1247
 
        
1248
 
        >>> c.interpolation = False
1249
 
        >>> c['section']['a'] == '%(datadir)s\\\\some path\\\\file.py'
1250
 
        1
1251
 
        >>> c['section']['b'] == '%(userdir)s\\\\some path\\\\file.py'
1252
 
        1
1253
 
        >>> c['section']['c'] == 'Yo %(a)s'
1254
 
        1
1255
 
        
1256
 
        Testing the interpolation errors.
1257
 
        
1258
 
        >>> c.interpolation = True
1259
 
        >>> c['section']['d']
1260
 
        Traceback (most recent call last):
1261
 
        MissingInterpolationOption: missing option "not_here" in interpolation.
1262
 
        >>> c['section']['e']
1263
 
        Traceback (most recent call last):
1264
 
        InterpolationDepthError: max interpolation depth exceeded in value "%(c)s".
1265
 
        
1266
 
        Testing our quoting.
1267
 
        
1268
 
        >>> i._quote('\"""\'\'\'')
1269
 
        Traceback (most recent call last):
1270
 
        SyntaxError: EOF while scanning triple-quoted string
1271
 
        >>> try:
1272
 
        ...     i._quote('\\n', multiline=False)
1273
 
        ... except ConfigObjError, e:
1274
 
        ...    e.msg
1275
 
        'Value "\\n" cannot be safely quoted.'
1276
 
        >>> k._quote(' "\' ', multiline=False)
1277
 
        Traceback (most recent call last):
1278
 
        SyntaxError: EOL while scanning single-quoted string
1279
 
        
1280
 
        Testing with "stringify" off.
1281
 
        >>> c.stringify = False
1282
 
        >>> c['test'] = 1
1283
 
        Traceback (most recent call last):
1284
 
        TypeError: Value is not a string "1".
1285
 
        """
 
1503
        """Actually parse the config file."""
 
1504
        temp_list_values = self.list_values
 
1505
        if self.unrepr:
 
1506
            self.list_values = False
 
1507
 
1286
1508
        comment_list = []
1287
1509
        done_start = False
1288
1510
        this_section = self
1289
1511
        maxline = len(infile) - 1
1290
1512
        cur_index = -1
1291
1513
        reset_comment = False
 
1514
 
1292
1515
        while cur_index < maxline:
1293
1516
            if reset_comment:
1294
1517
                comment_list = []
1300
1523
                reset_comment = False
1301
1524
                comment_list.append(line)
1302
1525
                continue
 
1526
 
1303
1527
            if not done_start:
1304
1528
                # preserve initial comment
1305
1529
                self.initial_comment = comment_list
1306
1530
                comment_list = []
1307
1531
                done_start = True
 
1532
 
1308
1533
            reset_comment = True
1309
1534
            # first we check if it's a section marker
1310
1535
            mat = self._sectionmarker.match(line)
1311
 
##            print >> sys.stderr, sline, mat
1312
1536
            if mat is not None:
1313
1537
                # is a section line
1314
 
                (indent, sect_open, sect_name, sect_close, comment) = (
1315
 
                    mat.groups())
 
1538
                (indent, sect_open, sect_name, sect_close, comment) = mat.groups()
1316
1539
                if indent and (self.indent_type is None):
1317
 
                    self.indent_type = indent[0]
 
1540
                    self.indent_type = indent
1318
1541
                cur_depth = sect_open.count('[')
1319
1542
                if cur_depth != sect_close.count(']'):
1320
 
                    self._handle_error(
1321
 
                        "Cannot compute the section depth at line %s.",
1322
 
                        NestingError, infile, cur_index)
 
1543
                    self._handle_error("Cannot compute the section depth at line %s.",
 
1544
                                       NestingError, infile, cur_index)
1323
1545
                    continue
 
1546
 
1324
1547
                if cur_depth < this_section.depth:
1325
1548
                    # the new section is dropping back to a previous level
1326
1549
                    try:
1327
 
                        parent = self._match_depth(
1328
 
                            this_section,
1329
 
                            cur_depth).parent
 
1550
                        parent = self._match_depth(this_section,
 
1551
                                                   cur_depth).parent
1330
1552
                    except SyntaxError:
1331
 
                        self._handle_error(
1332
 
                            "Cannot compute nesting level at line %s.",
1333
 
                            NestingError, infile, cur_index)
 
1553
                        self._handle_error("Cannot compute nesting level at line %s.",
 
1554
                                           NestingError, infile, cur_index)
1334
1555
                        continue
1335
1556
                elif cur_depth == this_section.depth:
1336
1557
                    # the new section is a sibling of the current section
1339
1560
                    # the new section is a child the current section
1340
1561
                    parent = this_section
1341
1562
                else:
1342
 
                    self._handle_error(
1343
 
                        "Section too nested at line %s.",
1344
 
                        NestingError, infile, cur_index)
1345
 
                #
 
1563
                    self._handle_error("Section too nested at line %s.",
 
1564
                                       NestingError, infile, cur_index)
 
1565
 
1346
1566
                sect_name = self._unquote(sect_name)
1347
1567
                if sect_name in parent:
1348
 
##                    print >> sys.stderr, sect_name
1349
 
                    self._handle_error(
1350
 
                        'Duplicate section name at line %s.',
1351
 
                        DuplicateError, infile, cur_index)
 
1568
                    self._handle_error('Duplicate section name at line %s.',
 
1569
                                       DuplicateError, infile, cur_index)
1352
1570
                    continue
 
1571
 
1353
1572
                # create the new section
1354
1573
                this_section = Section(
1355
1574
                    parent,
1359
1578
                parent[sect_name] = this_section
1360
1579
                parent.inline_comments[sect_name] = comment
1361
1580
                parent.comments[sect_name] = comment_list
1362
 
##                print >> sys.stderr, parent[sect_name] is this_section
1363
1581
                continue
1364
1582
            #
1365
1583
            # it's not a section marker,
1366
1584
            # so it should be a valid ``key = value`` line
1367
1585
            mat = self._keyword.match(line)
1368
 
##            print >> sys.stderr, sline, mat
1369
 
            if mat is not None:
 
1586
            if mat is None:
 
1587
                # it neither matched as a keyword
 
1588
                # or a section marker
 
1589
                self._handle_error(
 
1590
                    'Invalid line at line "%s".',
 
1591
                    ParseError, infile, cur_index)
 
1592
            else:
1370
1593
                # is a keyword value
1371
1594
                # value will include any inline comment
1372
1595
                (indent, key, value) = mat.groups()
1373
1596
                if indent and (self.indent_type is None):
1374
 
                    self.indent_type = indent[0]
 
1597
                    self.indent_type = indent
1375
1598
                # check for a multiline value
1376
1599
                if value[:3] in ['"""', "'''"]:
1377
1600
                    try:
1382
1605
                            'Parse error in value at line %s.',
1383
1606
                            ParseError, infile, cur_index)
1384
1607
                        continue
 
1608
                    else:
 
1609
                        if self.unrepr:
 
1610
                            comment = ''
 
1611
                            try:
 
1612
                                value = unrepr(value)
 
1613
                            except Exception, e:
 
1614
                                if type(e) == UnknownType:
 
1615
                                    msg = 'Unknown name or type in value at line %s.'
 
1616
                                else:
 
1617
                                    msg = 'Parse error in value at line %s.'
 
1618
                                self._handle_error(msg, UnreprError, infile,
 
1619
                                    cur_index)
 
1620
                                continue
1385
1621
                else:
1386
 
                    # extract comment and lists
1387
 
                    try:
1388
 
                        (value, comment) = self._handle_value(value)
1389
 
                    except SyntaxError:
1390
 
                        self._handle_error(
1391
 
                            'Parse error in value at line %s.',
1392
 
                            ParseError, infile, cur_index)
1393
 
                        continue
 
1622
                    if self.unrepr:
 
1623
                        comment = ''
 
1624
                        try:
 
1625
                            value = unrepr(value)
 
1626
                        except Exception, e:
 
1627
                            if isinstance(e, UnknownType):
 
1628
                                msg = 'Unknown name or type in value at line %s.'
 
1629
                            else:
 
1630
                                msg = 'Parse error in value at line %s.'
 
1631
                            self._handle_error(msg, UnreprError, infile,
 
1632
                                cur_index)
 
1633
                            continue
 
1634
                    else:
 
1635
                        # extract comment and lists
 
1636
                        try:
 
1637
                            (value, comment) = self._handle_value(value)
 
1638
                        except SyntaxError:
 
1639
                            self._handle_error(
 
1640
                                'Parse error in value at line %s.',
 
1641
                                ParseError, infile, cur_index)
 
1642
                            continue
1394
1643
                #
1395
 
##                print >> sys.stderr, sline
1396
1644
                key = self._unquote(key)
1397
1645
                if key in this_section:
1398
1646
                    self._handle_error(
1399
1647
                        'Duplicate keyword name at line %s.',
1400
1648
                        DuplicateError, infile, cur_index)
1401
1649
                    continue
1402
 
                # add the key
1403
 
##                print >> sys.stderr, this_section.name
1404
 
                this_section[key] = value
 
1650
                # add the key.
 
1651
                # we set unrepr because if we have got this far we will never
 
1652
                # be creating a new section
 
1653
                this_section.__setitem__(key, value, unrepr=True)
1405
1654
                this_section.inline_comments[key] = comment
1406
1655
                this_section.comments[key] = comment_list
1407
 
##                print >> sys.stderr, key, this_section[key]
1408
 
##                if this_section.name is not None:
1409
 
##                    print >> sys.stderr, this_section
1410
 
##                    print >> sys.stderr, this_section.parent
1411
 
##                    print >> sys.stderr, this_section.parent[this_section.name]
1412
1656
                continue
1413
 
            #
1414
 
            # it neither matched as a keyword
1415
 
            # or a section marker
1416
 
            self._handle_error(
1417
 
                'Invalid line at line "%s".',
1418
 
                ParseError, infile, cur_index)
 
1657
        #
1419
1658
        if self.indent_type is None:
1420
1659
            # no indentation used, set the type accordingly
1421
1660
            self.indent_type = ''
 
1661
 
1422
1662
        # preserve the final comment
1423
1663
        if not self and not self.initial_comment:
1424
1664
            self.initial_comment = comment_list
1425
 
        else:
 
1665
        elif not reset_comment:
1426
1666
            self.final_comment = comment_list
 
1667
        self.list_values = temp_list_values
 
1668
 
1427
1669
 
1428
1670
    def _match_depth(self, sect, depth):
1429
1671
        """
1430
1672
        Given a section and a depth level, walk back through the sections
1431
1673
        parents to see if the depth level matches a previous section.
1432
 
        
 
1674
 
1433
1675
        Return a reference to the right section,
1434
1676
        or raise a SyntaxError.
1435
1677
        """
1436
1678
        while depth < sect.depth:
1437
1679
            if sect is sect.parent:
1438
1680
                # we've reached the top level already
1439
 
                raise SyntaxError
 
1681
                raise SyntaxError()
1440
1682
            sect = sect.parent
1441
1683
        if sect.depth == depth:
1442
1684
            return sect
1443
1685
        # shouldn't get here
1444
 
        raise SyntaxError
 
1686
        raise SyntaxError()
 
1687
 
1445
1688
 
1446
1689
    def _handle_error(self, text, ErrorClass, infile, cur_index):
1447
1690
        """
1448
1691
        Handle an error according to the error settings.
1449
 
        
 
1692
 
1450
1693
        Either raise the error or store it.
1451
1694
        The error will have occured at ``cur_index``
1452
1695
        """
1453
1696
        line = infile[cur_index]
 
1697
        cur_index += 1
1454
1698
        message = text % cur_index
1455
1699
        error = ErrorClass(message, cur_index, line)
1456
1700
        if self.raise_errors:
1460
1704
        # reraise when parsing has finished
1461
1705
        self._errors.append(error)
1462
1706
 
 
1707
 
1463
1708
    def _unquote(self, value):
1464
1709
        """Return an unquoted version of a value"""
1465
1710
        if (value[0] == value[-1]) and (value[0] in ('"', "'")):
1466
1711
            value = value[1:-1]
1467
1712
        return value
1468
1713
 
 
1714
 
1469
1715
    def _quote(self, value, multiline=True):
1470
1716
        """
1471
1717
        Return a safely quoted version of a value.
1472
 
        
 
1718
 
1473
1719
        Raise a ConfigObjError if the value cannot be safely quoted.
1474
1720
        If multiline is ``True`` (default) then use triple quotes
1475
1721
        if necessary.
1476
 
        
1477
 
        Don't quote values that don't need it.
1478
 
        Recursively quote members of a list and return a comma joined list.
1479
 
        Multiline is ``False`` for lists.
1480
 
        Obey list syntax for empty and single member lists.
1481
 
        
 
1722
 
 
1723
        * Don't quote values that don't need it.
 
1724
        * Recursively quote members of a list and return a comma joined list.
 
1725
        * Multiline is ``False`` for lists.
 
1726
        * Obey list syntax for empty and single member lists.
 
1727
 
1482
1728
        If ``list_values=False`` then the value is only quoted if it contains
1483
 
        a ``\n`` (is multiline).
 
1729
        a ``\\n`` (is multiline) or '#'.
 
1730
 
 
1731
        If ``write_empty_values`` is set, and the value is an empty string, it
 
1732
        won't be quoted.
1484
1733
        """
1485
 
        if isinstance(value, (list, tuple)):
 
1734
        if multiline and self.write_empty_values and value == '':
 
1735
            # Only if multiline is set, so that it is used for values not
 
1736
            # keys, and not values that are part of a list
 
1737
            return ''
 
1738
 
 
1739
        if multiline and isinstance(value, (list, tuple)):
1486
1740
            if not value:
1487
1741
                return ','
1488
1742
            elif len(value) == 1:
1489
1743
                return self._quote(value[0], multiline=False) + ','
1490
1744
            return ', '.join([self._quote(val, multiline=False)
1491
1745
                for val in value])
1492
 
        if not isinstance(value, StringTypes):
 
1746
        if not isinstance(value, basestring):
1493
1747
            if self.stringify:
1494
1748
                value = str(value)
1495
1749
            else:
1496
 
                raise TypeError, 'Value "%s" is not a string.' % value
1497
 
        squot = "'%s'"
1498
 
        dquot = '"%s"'
1499
 
        noquot = "%s"
1500
 
        wspace_plus = ' \r\t\n\v\t\'"'
1501
 
        tsquot = '"""%s"""'
1502
 
        tdquot = "'''%s'''"
 
1750
                raise TypeError('Value "%s" is not a string.' % value)
 
1751
 
1503
1752
        if not value:
1504
1753
            return '""'
1505
 
        if (not self.list_values and '\n' not in value) or not (multiline and
1506
 
                ((("'" in value) and ('"' in value)) or ('\n' in value))):
 
1754
 
 
1755
        no_lists_no_quotes = not self.list_values and '\n' not in value and '#' not in value
 
1756
        need_triple = multiline and ((("'" in value) and ('"' in value)) or ('\n' in value ))
 
1757
        hash_triple_quote = multiline and not need_triple and ("'" in value) and ('"' in value) and ('#' in value)
 
1758
        check_for_single = (no_lists_no_quotes or not need_triple) and not hash_triple_quote
 
1759
 
 
1760
        if check_for_single:
1507
1761
            if not self.list_values:
1508
1762
                # we don't quote if ``list_values=False``
1509
1763
                quot = noquot
1510
1764
            # for normal values either single or double quotes will do
1511
1765
            elif '\n' in value:
1512
1766
                # will only happen if multiline is off - e.g. '\n' in key
1513
 
                raise ConfigObjError, ('Value "%s" cannot be safely quoted.' %
1514
 
                    value)
 
1767
                raise ConfigObjError('Value "%s" cannot be safely quoted.' % value)
1515
1768
            elif ((value[0] not in wspace_plus) and
1516
1769
                    (value[-1] not in wspace_plus) and
1517
1770
                    (',' not in value)):
1518
1771
                quot = noquot
1519
1772
            else:
1520
 
                if ("'" in value) and ('"' in value):
1521
 
                    raise ConfigObjError, (
1522
 
                        'Value "%s" cannot be safely quoted.' % value)
1523
 
                elif '"' in value:
1524
 
                    quot = squot
1525
 
                else:
1526
 
                    quot = dquot
 
1773
                quot = self._get_single_quote(value)
1527
1774
        else:
1528
1775
            # if value has '\n' or "'" *and* '"', it will need triple quotes
1529
 
            if (value.find('"""') != -1) and (value.find("'''") != -1):
1530
 
                raise ConfigObjError, (
1531
 
                    'Value "%s" cannot be safely quoted.' % value)
1532
 
            if value.find('"""') == -1:
1533
 
                quot = tdquot
1534
 
            else:
1535
 
                quot = tsquot
 
1776
            quot = self._get_triple_quote(value)
 
1777
 
 
1778
        if quot == noquot and '#' in value and self.list_values:
 
1779
            quot = self._get_single_quote(value)
 
1780
 
1536
1781
        return quot % value
1537
1782
 
 
1783
 
 
1784
    def _get_single_quote(self, value):
 
1785
        if ("'" in value) and ('"' in value):
 
1786
            raise ConfigObjError('Value "%s" cannot be safely quoted.' % value)
 
1787
        elif '"' in value:
 
1788
            quot = squot
 
1789
        else:
 
1790
            quot = dquot
 
1791
        return quot
 
1792
 
 
1793
 
 
1794
    def _get_triple_quote(self, value):
 
1795
        if (value.find('"""') != -1) and (value.find("'''") != -1):
 
1796
            raise ConfigObjError('Value "%s" cannot be safely quoted.' % value)
 
1797
        # upstream version (up to version 4.7.2) has the bug with incorrect quoting;
 
1798
        # fixed in our copy based on the suggestion of ConfigObj's author
 
1799
        if value.find('"""') == -1:
 
1800
            quot = tsquot
 
1801
        else:
 
1802
            quot = tdquot
 
1803
        return quot
 
1804
 
 
1805
 
1538
1806
    def _handle_value(self, value):
1539
1807
        """
1540
1808
        Given a value string, unquote, remove comment,
1541
1809
        handle lists. (including empty and single member lists)
1542
 
        
1543
 
        Testing list values.
1544
 
        
1545
 
        >>> testconfig3 = '''
1546
 
        ... a = ,
1547
 
        ... b = test,
1548
 
        ... c = test1, test2   , test3
1549
 
        ... d = test1, test2, test3,
1550
 
        ... '''
1551
 
        >>> d = ConfigObj(testconfig3.split('\\n'), raise_errors=True)
1552
 
        >>> d['a'] == []
1553
 
        1
1554
 
        >>> d['b'] == ['test']
1555
 
        1
1556
 
        >>> d['c'] == ['test1', 'test2', 'test3']
1557
 
        1
1558
 
        >>> d['d'] == ['test1', 'test2', 'test3']
1559
 
        1
1560
 
        
1561
 
        Testing with list values off.
1562
 
        
1563
 
        >>> e = ConfigObj(
1564
 
        ...     testconfig3.split('\\n'),
1565
 
        ...     raise_errors=True,
1566
 
        ...     list_values=False)
1567
 
        >>> e['a'] == ','
1568
 
        1
1569
 
        >>> e['b'] == 'test,'
1570
 
        1
1571
 
        >>> e['c'] == 'test1, test2   , test3'
1572
 
        1
1573
 
        >>> e['d'] == 'test1, test2, test3,'
1574
 
        1
1575
 
        
1576
 
        Testing creating from a dictionary.
1577
 
        
1578
 
        >>> f = {
1579
 
        ...     'key1': 'val1',
1580
 
        ...     'key2': 'val2',
1581
 
        ...     'section 1': {
1582
 
        ...         'key1': 'val1',
1583
 
        ...         'key2': 'val2',
1584
 
        ...         'section 1b': {
1585
 
        ...             'key1': 'val1',
1586
 
        ...             'key2': 'val2',
1587
 
        ...         },
1588
 
        ...     },
1589
 
        ...     'section 2': {
1590
 
        ...         'key1': 'val1',
1591
 
        ...         'key2': 'val2',
1592
 
        ...         'section 2b': {
1593
 
        ...             'key1': 'val1',
1594
 
        ...             'key2': 'val2',
1595
 
        ...         },
1596
 
        ...     },
1597
 
        ...      'key3': 'val3',
1598
 
        ... }
1599
 
        >>> g = ConfigObj(f)
1600
 
        >>> f == g
1601
 
        1
1602
 
        
1603
 
        Testing we correctly detect badly built list values (4 of them).
1604
 
        
1605
 
        >>> testconfig4 = '''
1606
 
        ... config = 3,4,,
1607
 
        ... test = 3,,4
1608
 
        ... fish = ,,
1609
 
        ... dummy = ,,hello, goodbye
1610
 
        ... '''
1611
 
        >>> try:
1612
 
        ...     ConfigObj(testconfig4.split('\\n'))
1613
 
        ... except ConfigObjError, e:
1614
 
        ...     len(e.errors)
1615
 
        4
1616
 
        
1617
 
        Testing we correctly detect badly quoted values (4 of them).
1618
 
        
1619
 
        >>> testconfig5 = '''
1620
 
        ... config = "hello   # comment
1621
 
        ... test = 'goodbye
1622
 
        ... fish = 'goodbye   # comment
1623
 
        ... dummy = "hello again
1624
 
        ... '''
1625
 
        >>> try:
1626
 
        ...     ConfigObj(testconfig5.split('\\n'))
1627
 
        ... except ConfigObjError, e:
1628
 
        ...     len(e.errors)
1629
 
        4
1630
1810
        """
 
1811
        if self._inspec:
 
1812
            # Parsing a configspec so don't handle comments
 
1813
            return (value, '')
1631
1814
        # do we look for lists in values ?
1632
1815
        if not self.list_values:
1633
1816
            mat = self._nolistvalue.match(value)
1634
1817
            if mat is None:
1635
 
                raise SyntaxError
1636
 
            (value, comment) = mat.groups()
 
1818
                raise SyntaxError()
1637
1819
            # NOTE: we don't unquote here
1638
 
            return (value, comment)
 
1820
            return mat.groups()
 
1821
        #
1639
1822
        mat = self._valueexp.match(value)
1640
1823
        if mat is None:
1641
1824
            # the value is badly constructed, probably badly quoted,
1642
1825
            # or an invalid list
1643
 
            raise SyntaxError
 
1826
            raise SyntaxError()
1644
1827
        (list_values, single, empty_list, comment) = mat.groups()
1645
1828
        if (list_values == '') and (single is None):
1646
1829
            # change this if you want to accept empty values
1647
 
            raise SyntaxError
 
1830
            raise SyntaxError()
1648
1831
        # NOTE: note there is no error handling from here if the regex
1649
1832
        # is wrong: then incorrect values will slip through
1650
1833
        if empty_list is not None:
1651
1834
            # the single comma - meaning an empty list
1652
1835
            return ([], comment)
1653
1836
        if single is not None:
1654
 
            single = self._unquote(single)
 
1837
            # handle empty values
 
1838
            if list_values and not single:
 
1839
                # FIXME: the '' is a workaround because our regex now matches
 
1840
                #   '' at the end of a list if it has a trailing comma
 
1841
                single = None
 
1842
            else:
 
1843
                single = single or '""'
 
1844
                single = self._unquote(single)
1655
1845
        if list_values == '':
1656
1846
            # not a list value
1657
1847
            return (single, comment)
1661
1851
            the_list += [single]
1662
1852
        return (the_list, comment)
1663
1853
 
 
1854
 
1664
1855
    def _multiline(self, value, infile, cur_index, maxline):
1665
 
        """
1666
 
        Extract the value, where we are in a multiline situation
1667
 
        
1668
 
        Testing multiline values.
1669
 
        
1670
 
        >>> i == {
1671
 
        ...     'name4': ' another single line value ',
1672
 
        ...     'multi section': {
1673
 
        ...         'name4': '\\n        Well, this is a\\n        multiline '
1674
 
        ...             'value\\n        ',
1675
 
        ...         'name2': '\\n        Well, this is a\\n        multiline '
1676
 
        ...             'value\\n        ',
1677
 
        ...         'name3': '\\n        Well, this is a\\n        multiline '
1678
 
        ...             'value\\n        ',
1679
 
        ...         'name1': '\\n        Well, this is a\\n        multiline '
1680
 
        ...             'value\\n        ',
1681
 
        ...     },
1682
 
        ...     'name2': ' another single line value ',
1683
 
        ...     'name3': ' a single line value ',
1684
 
        ...     'name1': ' a single line value ',
1685
 
        ... }
1686
 
        1
1687
 
        """
 
1856
        """Extract the value, where we are in a multiline situation."""
1688
1857
        quot = value[:3]
1689
1858
        newvalue = value[3:]
1690
1859
        single_line = self._triple_quote[quot][0]
1696
1865
            return retval
1697
1866
        elif newvalue.find(quot) != -1:
1698
1867
            # somehow the triple quote is missing
1699
 
            raise SyntaxError
 
1868
            raise SyntaxError()
1700
1869
        #
1701
1870
        while cur_index < maxline:
1702
1871
            cur_index += 1
1709
1878
                break
1710
1879
        else:
1711
1880
            # we've got to the end of the config, oops...
1712
 
            raise SyntaxError
 
1881
            raise SyntaxError()
1713
1882
        mat = multi_line.match(line)
1714
1883
        if mat is None:
1715
1884
            # a badly formed line
1716
 
            raise SyntaxError
 
1885
            raise SyntaxError()
1717
1886
        (value, comment) = mat.groups()
1718
1887
        return (newvalue + value, comment, cur_index)
1719
1888
 
 
1889
 
1720
1890
    def _handle_configspec(self, configspec):
1721
1891
        """Parse the configspec."""
1722
 
        try:
1723
 
            configspec = ConfigObj(
1724
 
                configspec,
1725
 
                raise_errors=True,
1726
 
                file_error=True,
1727
 
                list_values=False)
1728
 
        except ConfigObjError, e:
1729
 
            # FIXME: Should these errors have a reference
1730
 
            # to the already parsed ConfigObj ?
1731
 
            raise ConfigspecError('Parsing configspec failed: %s' % e)
1732
 
        except IOError, e:
1733
 
            raise IOError('Reading configspec failed: %s' % e)
1734
 
        self._set_configspec_value(configspec, self)
1735
 
 
1736
 
    def _set_configspec_value(self, configspec, section):
1737
 
        """Used to recursively set configspec values."""
1738
 
        if '__many__' in configspec.sections:
1739
 
            section.configspec['__many__'] = configspec['__many__']
1740
 
            if len(configspec.sections) > 1:
1741
 
                # FIXME: can we supply any useful information here ?
1742
 
                raise RepeatSectionError
1743
 
        for entry in configspec.scalars:
1744
 
            section.configspec[entry] = configspec[entry]
 
1892
        # FIXME: Should we check that the configspec was created with the
 
1893
        #        correct settings ? (i.e. ``list_values=False``)
 
1894
        if not isinstance(configspec, ConfigObj):
 
1895
            try:
 
1896
                configspec = ConfigObj(configspec,
 
1897
                                       raise_errors=True,
 
1898
                                       file_error=True,
 
1899
                                       _inspec=True)
 
1900
            except ConfigObjError, e:
 
1901
                # FIXME: Should these errors have a reference
 
1902
                #        to the already parsed ConfigObj ?
 
1903
                raise ConfigspecError('Parsing configspec failed: %s' % e)
 
1904
            except IOError, e:
 
1905
                raise IOError('Reading configspec failed: %s' % e)
 
1906
 
 
1907
        self.configspec = configspec
 
1908
 
 
1909
 
 
1910
 
 
1911
    def _set_configspec(self, section, copy):
 
1912
        """
 
1913
        Called by validate. Handles setting the configspec on subsections
 
1914
        including sections to be validated by __many__
 
1915
        """
 
1916
        configspec = section.configspec
 
1917
        many = configspec.get('__many__')
 
1918
        if isinstance(many, dict):
 
1919
            for entry in section.sections:
 
1920
                if entry not in configspec:
 
1921
                    section[entry].configspec = many
 
1922
 
1745
1923
        for entry in configspec.sections:
1746
1924
            if entry == '__many__':
1747
1925
                continue
1748
1926
            if entry not in section:
1749
1927
                section[entry] = {}
1750
 
            self._set_configspec_value(configspec[entry], section[entry])
1751
 
 
1752
 
    def _handle_repeat(self, section, configspec):
1753
 
        """Dynamically assign configspec for repeated section."""
1754
 
        try:
1755
 
            section_keys = configspec.sections
1756
 
            scalar_keys = configspec.scalars
1757
 
        except AttributeError:
1758
 
            section_keys = [entry for entry in configspec 
1759
 
                                if isinstance(configspec[entry], dict)]
1760
 
            scalar_keys = [entry for entry in configspec 
1761
 
                                if not isinstance(configspec[entry], dict)]
1762
 
        if '__many__' in section_keys and len(section_keys) > 1:
1763
 
            # FIXME: can we supply any useful information here ?
1764
 
            raise RepeatSectionError
1765
 
        scalars = {}
1766
 
        sections = {}
1767
 
        for entry in scalar_keys:
1768
 
            val = configspec[entry]
1769
 
            scalars[entry] = val
1770
 
        for entry in section_keys:
1771
 
            val = configspec[entry]
1772
 
            if entry == '__many__':
1773
 
                scalars[entry] = val
1774
 
                continue
1775
 
            sections[entry] = val
1776
 
        #
1777
 
        section.configspec = scalars
1778
 
        for entry in sections:
1779
 
            if entry not in section:
1780
 
                section[entry] = {}
1781
 
            self._handle_repeat(section[entry], sections[entry])
 
1928
                if copy:
 
1929
                    # copy comments
 
1930
                    section.comments[entry] = configspec.comments.get(entry, [])
 
1931
                    section.inline_comments[entry] = configspec.inline_comments.get(entry, '')
 
1932
 
 
1933
            # Could be a scalar when we expect a section
 
1934
            if isinstance(section[entry], Section):
 
1935
                section[entry].configspec = configspec[entry]
 
1936
 
1782
1937
 
1783
1938
    def _write_line(self, indent_string, entry, this_entry, comment):
1784
1939
        """Write an individual line, for the write method"""
1785
1940
        # NOTE: the calls to self._quote here handles non-StringType values.
1786
 
        return '%s%s%s%s%s' % (
1787
 
            indent_string,
1788
 
            self._decode_element(self._quote(entry, multiline=False)),
1789
 
            self._a_to_u(' = '),
1790
 
            self._decode_element(self._quote(this_entry)),
1791
 
            self._decode_element(comment))
 
1941
        if not self.unrepr:
 
1942
            val = self._decode_element(self._quote(this_entry))
 
1943
        else:
 
1944
            val = repr(this_entry)
 
1945
        return '%s%s%s%s%s' % (indent_string,
 
1946
                               self._decode_element(self._quote(entry, multiline=False)),
 
1947
                               self._a_to_u(' = '),
 
1948
                               val,
 
1949
                               self._decode_element(comment))
 
1950
 
1792
1951
 
1793
1952
    def _write_marker(self, indent_string, depth, entry, comment):
1794
1953
        """Write a section marker line"""
1795
 
        return '%s%s%s%s%s' % (
1796
 
            indent_string,
1797
 
            self._a_to_u('[' * depth),
1798
 
            self._quote(self._decode_element(entry), multiline=False),
1799
 
            self._a_to_u(']' * depth),
1800
 
            self._decode_element(comment))
 
1954
        return '%s%s%s%s%s' % (indent_string,
 
1955
                               self._a_to_u('[' * depth),
 
1956
                               self._quote(self._decode_element(entry), multiline=False),
 
1957
                               self._a_to_u(']' * depth),
 
1958
                               self._decode_element(comment))
 
1959
 
1801
1960
 
1802
1961
    def _handle_comment(self, comment):
1803
 
        """
1804
 
        Deal with a comment.
1805
 
        
1806
 
        >>> filename = a.filename
1807
 
        >>> a.filename = None
1808
 
        >>> values = a.write()
1809
 
        >>> index = 0
1810
 
        >>> while index < 23:
1811
 
        ...     index += 1
1812
 
        ...     line = values[index-1]
1813
 
        ...     assert line.endswith('# comment ' + str(index))
1814
 
        >>> a.filename = filename
1815
 
        
1816
 
        >>> start_comment = ['# Initial Comment', '', '#']
1817
 
        >>> end_comment = ['', '#', '# Final Comment']
1818
 
        >>> newconfig = start_comment + testconfig1.split('\\n') + end_comment
1819
 
        >>> nc = ConfigObj(newconfig)
1820
 
        >>> nc.initial_comment
1821
 
        ['# Initial Comment', '', '#']
1822
 
        >>> nc.final_comment
1823
 
        ['', '#', '# Final Comment']
1824
 
        >>> nc.initial_comment == start_comment
1825
 
        1
1826
 
        >>> nc.final_comment == end_comment
1827
 
        1
1828
 
        """
 
1962
        """Deal with a comment."""
1829
1963
        if not comment:
1830
1964
            return ''
1831
 
        if self.indent_type == '\t':
1832
 
            start = self._a_to_u('\t')
1833
 
        else:
1834
 
            start = self._a_to_u(' ' * NUM_INDENT_SPACES)
 
1965
        start = self.indent_type
1835
1966
        if not comment.startswith('#'):
1836
 
            start += _a_to_u('# ')
 
1967
            start += self._a_to_u(' # ')
1837
1968
        return (start + comment)
1838
1969
 
1839
 
    def _compute_indent_string(self, depth):
1840
 
        """
1841
 
        Compute the indent string, according to current indent_type and depth
1842
 
        """
1843
 
        if self.indent_type == '':
1844
 
            # no indentation at all
1845
 
            return ''
1846
 
        if self.indent_type == '\t':
1847
 
            return '\t' * depth
1848
 
        if self.indent_type == ' ':
1849
 
            return ' ' * NUM_INDENT_SPACES * depth
1850
 
        raise SyntaxError
1851
1970
 
1852
1971
    # Public methods
1853
1972
 
1854
1973
    def write(self, outfile=None, section=None):
1855
1974
        """
1856
1975
        Write the current ConfigObj as a file
1857
 
        
 
1976
 
1858
1977
        tekNico: FIXME: use StringIO instead of real files
1859
 
        
 
1978
 
1860
1979
        >>> filename = a.filename
1861
1980
        >>> a.filename = 'test.ini'
1862
1981
        >>> a.write()
1863
1982
        >>> a.filename = filename
1864
1983
        >>> a == ConfigObj('test.ini', raise_errors=True)
1865
1984
        1
1866
 
        >>> os.remove('test.ini')
1867
 
        >>> b.filename = 'test.ini'
1868
 
        >>> b.write()
1869
 
        >>> b == ConfigObj('test.ini', raise_errors=True)
1870
 
        1
1871
 
        >>> os.remove('test.ini')
1872
 
        >>> i.filename = 'test.ini'
1873
 
        >>> i.write()
1874
 
        >>> i == ConfigObj('test.ini', raise_errors=True)
1875
 
        1
1876
 
        >>> os.remove('test.ini')
1877
 
        >>> a = ConfigObj()
1878
 
        >>> a['DEFAULT'] = {'a' : 'fish'}
1879
 
        >>> a['a'] = '%(a)s'
1880
 
        >>> a.write()
1881
 
        ['a = %(a)s', '[DEFAULT]', 'a = fish']
1882
1985
        """
1883
1986
        if self.indent_type is None:
1884
1987
            # this can be true if initialised from a dictionary
1885
1988
            self.indent_type = DEFAULT_INDENT_TYPE
1886
 
        #
 
1989
 
1887
1990
        out = []
1888
1991
        cs = self._a_to_u('#')
1889
1992
        csp = self._a_to_u('# ')
1897
2000
                if stripped_line and not stripped_line.startswith(cs):
1898
2001
                    line = csp + line
1899
2002
                out.append(line)
1900
 
        #
1901
 
        indent_string = self._a_to_u(
1902
 
            self._compute_indent_string(section.depth))
 
2003
 
 
2004
        indent_string = self.indent_type * section.depth
1903
2005
        for entry in (section.scalars + section.sections):
1904
2006
            if entry in section.defaults:
1905
2007
                # don't write out default values
1911
2013
                out.append(indent_string + comment_line)
1912
2014
            this_entry = section[entry]
1913
2015
            comment = self._handle_comment(section.inline_comments[entry])
1914
 
            #
 
2016
 
1915
2017
            if isinstance(this_entry, dict):
1916
2018
                # a section
1917
2019
                out.append(self._write_marker(
1926
2028
                    entry,
1927
2029
                    this_entry,
1928
2030
                    comment))
1929
 
        #
 
2031
 
1930
2032
        if section is self:
1931
2033
            for line in self.final_comment:
1932
2034
                line = self._decode_element(line)
1935
2037
                    line = csp + line
1936
2038
                out.append(line)
1937
2039
            self.interpolation = int_val
1938
 
        #
 
2040
 
1939
2041
        if section is not self:
1940
2042
            return out
1941
 
        #
 
2043
 
1942
2044
        if (self.filename is None) and (outfile is None):
1943
2045
            # output a list of lines
1944
2046
            # might need to encode
1952
2054
                    out.append('')
1953
2055
                out[0] = BOM_UTF8 + out[0]
1954
2056
            return out
1955
 
        #
 
2057
 
1956
2058
        # Turn the list to a string, joined with correct newlines
1957
 
        output = (self._a_to_u(self.newlines or os.linesep)
1958
 
            ).join(out)
 
2059
        newline = self.newlines or os.linesep
 
2060
        output = self._a_to_u(newline).join(out)
1959
2061
        if self.encoding:
1960
2062
            output = output.encode(self.encoding)
1961
 
        if (self.BOM and ((self.encoding is None) or
1962
 
            (BOM_LIST.get(self.encoding.lower()) == 'utf_8'))):
 
2063
        if self.BOM and ((self.encoding is None) or match_utf8(self.encoding)):
1963
2064
            # Add the UTF8 BOM
1964
2065
            output = BOM_UTF8 + output
 
2066
 
 
2067
        if not output.endswith(newline):
 
2068
            output += newline
1965
2069
        if outfile is not None:
1966
2070
            outfile.write(output)
1967
2071
        else:
1968
 
            h = open(self.filename, 'w')
 
2072
            h = open(self.filename, 'wb')
1969
2073
            h.write(output)
1970
2074
            h.close()
1971
2075
 
1972
 
    def validate(self, validator, preserve_errors=False, section=None):
 
2076
 
 
2077
    def validate(self, validator, preserve_errors=False, copy=False,
 
2078
                 section=None):
1973
2079
        """
1974
2080
        Test the ConfigObj against a configspec.
1975
 
        
 
2081
 
1976
2082
        It uses the ``validator`` object from *validate.py*.
1977
 
        
 
2083
 
1978
2084
        To run ``validate`` on the current ConfigObj, call: ::
1979
 
        
 
2085
 
1980
2086
            test = config.validate(validator)
1981
 
        
 
2087
 
1982
2088
        (Normally having previously passed in the configspec when the ConfigObj
1983
2089
        was created - you can dynamically assign a dictionary of checks to the
1984
2090
        ``configspec`` attribute of a section though).
1985
 
        
 
2091
 
1986
2092
        It returns ``True`` if everything passes, or a dictionary of
1987
2093
        pass/fails (True/False). If every member of a subsection passes, it
1988
2094
        will just have the value ``True``. (It also returns ``False`` if all
1989
2095
        members fail).
1990
 
        
 
2096
 
1991
2097
        In addition, it converts the values from strings to their native
1992
2098
        types if their checks pass (and ``stringify`` is set).
1993
 
        
 
2099
 
1994
2100
        If ``preserve_errors`` is ``True`` (``False`` is default) then instead
1995
2101
        of a marking a fail with a ``False``, it will preserve the actual
1996
2102
        exception object. This can contain info about the reason for failure.
1997
 
        For example the ``VdtValueTooSmallError`` indeicates that the value
 
2103
        For example the ``VdtValueTooSmallError`` indicates that the value
1998
2104
        supplied was too small. If a value (or section) is missing it will
1999
2105
        still be marked as ``False``.
2000
 
        
 
2106
 
2001
2107
        You must have the validate module to use ``preserve_errors=True``.
2002
 
        
 
2108
 
2003
2109
        You can then use the ``flatten_errors`` function to turn your nested
2004
2110
        results dictionary into a flattened list of failures - useful for
2005
2111
        displaying meaningful error messages.
2006
 
        
2007
 
        >>> try:
2008
 
        ...     from validate import Validator
2009
 
        ... except ImportError:
2010
 
        ...     print >> sys.stderr, 'Cannot import the Validator object, skipping the related tests'
2011
 
        ... else:
2012
 
        ...     config = '''
2013
 
        ...     test1=40
2014
 
        ...     test2=hello
2015
 
        ...     test3=3
2016
 
        ...     test4=5.0
2017
 
        ...     [section]
2018
 
        ...         test1=40
2019
 
        ...         test2=hello
2020
 
        ...         test3=3
2021
 
        ...         test4=5.0
2022
 
        ...         [[sub section]]
2023
 
        ...             test1=40
2024
 
        ...             test2=hello
2025
 
        ...             test3=3
2026
 
        ...             test4=5.0
2027
 
        ... '''.split('\\n')
2028
 
        ...     configspec = '''
2029
 
        ...     test1= integer(30,50)
2030
 
        ...     test2= string
2031
 
        ...     test3=integer
2032
 
        ...     test4=float(6.0)
2033
 
        ...     [section ]
2034
 
        ...         test1=integer(30,50)
2035
 
        ...         test2=string
2036
 
        ...         test3=integer
2037
 
        ...         test4=float(6.0)
2038
 
        ...         [[sub section]]
2039
 
        ...             test1=integer(30,50)
2040
 
        ...             test2=string
2041
 
        ...             test3=integer
2042
 
        ...             test4=float(6.0)
2043
 
        ...     '''.split('\\n')
2044
 
        ...     val = Validator()
2045
 
        ...     c1 = ConfigObj(config, configspec=configspec)
2046
 
        ...     test = c1.validate(val)
2047
 
        ...     test == {
2048
 
        ...         'test1': True,
2049
 
        ...         'test2': True,
2050
 
        ...         'test3': True,
2051
 
        ...         'test4': False,
2052
 
        ...         'section': {
2053
 
        ...             'test1': True,
2054
 
        ...             'test2': True,
2055
 
        ...             'test3': True,
2056
 
        ...             'test4': False,
2057
 
        ...             'sub section': {
2058
 
        ...                 'test1': True,
2059
 
        ...                 'test2': True,
2060
 
        ...                 'test3': True,
2061
 
        ...                 'test4': False,
2062
 
        ...             },
2063
 
        ...         },
2064
 
        ...     }
2065
 
        1
2066
 
        >>> val.check(c1.configspec['test4'], c1['test4'])
2067
 
        Traceback (most recent call last):
2068
 
        VdtValueTooSmallError: the value "5.0" is too small.
2069
 
        
2070
 
        >>> val_test_config = '''
2071
 
        ...     key = 0
2072
 
        ...     key2 = 1.1
2073
 
        ...     [section]
2074
 
        ...     key = some text
2075
 
        ...     key2 = 1.1, 3.0, 17, 6.8
2076
 
        ...         [[sub-section]]
2077
 
        ...         key = option1
2078
 
        ...         key2 = True'''.split('\\n')
2079
 
        >>> val_test_configspec = '''
2080
 
        ...     key = integer
2081
 
        ...     key2 = float
2082
 
        ...     [section]
2083
 
        ...     key = string
2084
 
        ...     key2 = float_list(4)
2085
 
        ...        [[sub-section]]
2086
 
        ...        key = option(option1, option2)
2087
 
        ...        key2 = boolean'''.split('\\n')
2088
 
        >>> val_test = ConfigObj(val_test_config, configspec=val_test_configspec)
2089
 
        >>> val_test.validate(val)
2090
 
        1
2091
 
        >>> val_test['key'] = 'text not a digit'
2092
 
        >>> val_res = val_test.validate(val)
2093
 
        >>> val_res == {'key2': True, 'section': True, 'key': False}
2094
 
        1
2095
 
        >>> configspec = '''
2096
 
        ...     test1=integer(30,50, default=40)
2097
 
        ...     test2=string(default="hello")
2098
 
        ...     test3=integer(default=3)
2099
 
        ...     test4=float(6.0, default=6.0)
2100
 
        ...     [section ]
2101
 
        ...         test1=integer(30,50, default=40)
2102
 
        ...         test2=string(default="hello")
2103
 
        ...         test3=integer(default=3)
2104
 
        ...         test4=float(6.0, default=6.0)
2105
 
        ...         [[sub section]]
2106
 
        ...             test1=integer(30,50, default=40)
2107
 
        ...             test2=string(default="hello")
2108
 
        ...             test3=integer(default=3)
2109
 
        ...             test4=float(6.0, default=6.0)
2110
 
        ...     '''.split('\\n')
2111
 
        >>> default_test = ConfigObj(['test1=30'], configspec=configspec)
2112
 
        >>> default_test
2113
 
        {'test1': '30', 'section': {'sub section': {}}}
2114
 
        >>> default_test.validate(val)
2115
 
        1
2116
 
        >>> default_test == {
2117
 
        ...     'test1': 30,
2118
 
        ...     'test2': 'hello',
2119
 
        ...     'test3': 3,
2120
 
        ...     'test4': 6.0,
2121
 
        ...     'section': {
2122
 
        ...         'test1': 40,
2123
 
        ...         'test2': 'hello',
2124
 
        ...         'test3': 3,
2125
 
        ...         'test4': 6.0,
2126
 
        ...         'sub section': {
2127
 
        ...             'test1': 40,
2128
 
        ...             'test3': 3,
2129
 
        ...             'test2': 'hello',
2130
 
        ...             'test4': 6.0,
2131
 
        ...         },
2132
 
        ...     },
2133
 
        ... }
2134
 
        1
2135
 
        
2136
 
        Now testing with repeated sections : BIG TEST
2137
 
        
2138
 
        >>> repeated_1 = '''
2139
 
        ... [dogs]
2140
 
        ...     [[__many__]] # spec for a dog
2141
 
        ...         fleas = boolean(default=True)
2142
 
        ...         tail = option(long, short, default=long)
2143
 
        ...         name = string(default=rover)
2144
 
        ...         [[[__many__]]]  # spec for a puppy
2145
 
        ...             name = string(default="son of rover")
2146
 
        ...             age = float(default=0.0)
2147
 
        ... [cats]
2148
 
        ...     [[__many__]] # spec for a cat
2149
 
        ...         fleas = boolean(default=True)
2150
 
        ...         tail = option(long, short, default=short)
2151
 
        ...         name = string(default=pussy)
2152
 
        ...         [[[__many__]]] # spec for a kitten
2153
 
        ...             name = string(default="son of pussy")
2154
 
        ...             age = float(default=0.0)
2155
 
        ...         '''.split('\\n')
2156
 
        >>> repeated_2 = '''
2157
 
        ... [dogs]
2158
 
        ... 
2159
 
        ...     # blank dogs with puppies
2160
 
        ...     # should be filled in by the configspec
2161
 
        ...     [[dog1]]
2162
 
        ...         [[[puppy1]]]
2163
 
        ...         [[[puppy2]]]
2164
 
        ...         [[[puppy3]]]
2165
 
        ...     [[dog2]]
2166
 
        ...         [[[puppy1]]]
2167
 
        ...         [[[puppy2]]]
2168
 
        ...         [[[puppy3]]]
2169
 
        ...     [[dog3]]
2170
 
        ...         [[[puppy1]]]
2171
 
        ...         [[[puppy2]]]
2172
 
        ...         [[[puppy3]]]
2173
 
        ... [cats]
2174
 
        ... 
2175
 
        ...     # blank cats with kittens
2176
 
        ...     # should be filled in by the configspec
2177
 
        ...     [[cat1]]
2178
 
        ...         [[[kitten1]]]
2179
 
        ...         [[[kitten2]]]
2180
 
        ...         [[[kitten3]]]
2181
 
        ...     [[cat2]]
2182
 
        ...         [[[kitten1]]]
2183
 
        ...         [[[kitten2]]]
2184
 
        ...         [[[kitten3]]]
2185
 
        ...     [[cat3]]
2186
 
        ...         [[[kitten1]]]
2187
 
        ...         [[[kitten2]]]
2188
 
        ...         [[[kitten3]]]
2189
 
        ... '''.split('\\n')
2190
 
        >>> repeated_3 = '''
2191
 
        ... [dogs]
2192
 
        ... 
2193
 
        ...     [[dog1]]
2194
 
        ...     [[dog2]]
2195
 
        ...     [[dog3]]
2196
 
        ... [cats]
2197
 
        ... 
2198
 
        ...     [[cat1]]
2199
 
        ...     [[cat2]]
2200
 
        ...     [[cat3]]
2201
 
        ... '''.split('\\n')
2202
 
        >>> repeated_4 = '''
2203
 
        ... [__many__]
2204
 
        ... 
2205
 
        ...     name = string(default=Michael)
2206
 
        ...     age = float(default=0.0)
2207
 
        ...     sex = option(m, f, default=m)
2208
 
        ... '''.split('\\n')
2209
 
        >>> repeated_5 = '''
2210
 
        ... [cats]
2211
 
        ... [[__many__]]
2212
 
        ...     fleas = boolean(default=True)
2213
 
        ...     tail = option(long, short, default=short)
2214
 
        ...     name = string(default=pussy)
2215
 
        ...     [[[description]]]
2216
 
        ...         height = float(default=3.3)
2217
 
        ...         weight = float(default=6)
2218
 
        ...         [[[[coat]]]]
2219
 
        ...             fur = option(black, grey, brown, "tortoise shell", default=black)
2220
 
        ...             condition = integer(0,10, default=5)
2221
 
        ... '''.split('\\n')
2222
 
        >>> from validate import Validator
2223
 
        >>> val= Validator()
2224
 
        >>> repeater = ConfigObj(repeated_2, configspec=repeated_1)
2225
 
        >>> repeater.validate(val)
2226
 
        1
2227
 
        >>> repeater == {
2228
 
        ...     'dogs': {
2229
 
        ...         'dog1': {
2230
 
        ...             'fleas': True,
2231
 
        ...             'tail': 'long',
2232
 
        ...             'name': 'rover',
2233
 
        ...             'puppy1': {'name': 'son of rover', 'age': 0.0},
2234
 
        ...             'puppy2': {'name': 'son of rover', 'age': 0.0},
2235
 
        ...             'puppy3': {'name': 'son of rover', 'age': 0.0},
2236
 
        ...         },
2237
 
        ...         'dog2': {
2238
 
        ...             'fleas': True,
2239
 
        ...             'tail': 'long',
2240
 
        ...             'name': 'rover',
2241
 
        ...             'puppy1': {'name': 'son of rover', 'age': 0.0},
2242
 
        ...             'puppy2': {'name': 'son of rover', 'age': 0.0},
2243
 
        ...             'puppy3': {'name': 'son of rover', 'age': 0.0},
2244
 
        ...         },
2245
 
        ...         'dog3': {
2246
 
        ...             'fleas': True,
2247
 
        ...             'tail': 'long',
2248
 
        ...             'name': 'rover',
2249
 
        ...             'puppy1': {'name': 'son of rover', 'age': 0.0},
2250
 
        ...             'puppy2': {'name': 'son of rover', 'age': 0.0},
2251
 
        ...             'puppy3': {'name': 'son of rover', 'age': 0.0},
2252
 
        ...         },
2253
 
        ...     },
2254
 
        ...     'cats': {
2255
 
        ...         'cat1': {
2256
 
        ...             'fleas': True,
2257
 
        ...             'tail': 'short',
2258
 
        ...             'name': 'pussy',
2259
 
        ...             'kitten1': {'name': 'son of pussy', 'age': 0.0},
2260
 
        ...             'kitten2': {'name': 'son of pussy', 'age': 0.0},
2261
 
        ...             'kitten3': {'name': 'son of pussy', 'age': 0.0},
2262
 
        ...         },
2263
 
        ...         'cat2': {
2264
 
        ...             'fleas': True,
2265
 
        ...             'tail': 'short',
2266
 
        ...             'name': 'pussy',
2267
 
        ...             'kitten1': {'name': 'son of pussy', 'age': 0.0},
2268
 
        ...             'kitten2': {'name': 'son of pussy', 'age': 0.0},
2269
 
        ...             'kitten3': {'name': 'son of pussy', 'age': 0.0},
2270
 
        ...         },
2271
 
        ...         'cat3': {
2272
 
        ...             'fleas': True,
2273
 
        ...             'tail': 'short',
2274
 
        ...             'name': 'pussy',
2275
 
        ...             'kitten1': {'name': 'son of pussy', 'age': 0.0},
2276
 
        ...             'kitten2': {'name': 'son of pussy', 'age': 0.0},
2277
 
        ...             'kitten3': {'name': 'son of pussy', 'age': 0.0},
2278
 
        ...         },
2279
 
        ...     },
2280
 
        ... }
2281
 
        1
2282
 
        >>> repeater = ConfigObj(repeated_3, configspec=repeated_1)
2283
 
        >>> repeater.validate(val)
2284
 
        1
2285
 
        >>> repeater == {
2286
 
        ...     'cats': {
2287
 
        ...         'cat1': {'fleas': True, 'tail': 'short', 'name': 'pussy'},
2288
 
        ...         'cat2': {'fleas': True, 'tail': 'short', 'name': 'pussy'},
2289
 
        ...         'cat3': {'fleas': True, 'tail': 'short', 'name': 'pussy'},
2290
 
        ...     },
2291
 
        ...     'dogs': {
2292
 
        ...         'dog1': {'fleas': True, 'tail': 'long', 'name': 'rover'},
2293
 
        ...         'dog2': {'fleas': True, 'tail': 'long', 'name': 'rover'},
2294
 
        ...         'dog3': {'fleas': True, 'tail': 'long', 'name': 'rover'},
2295
 
        ...     },
2296
 
        ... }
2297
 
        1
2298
 
        >>> repeater = ConfigObj(configspec=repeated_4)
2299
 
        >>> repeater['Michael'] = {}
2300
 
        >>> repeater.validate(val)
2301
 
        1
2302
 
        >>> repeater == {
2303
 
        ...     'Michael': {'age': 0.0, 'name': 'Michael', 'sex': 'm'},
2304
 
        ... }
2305
 
        1
2306
 
        >>> repeater = ConfigObj(repeated_3, configspec=repeated_5)
2307
 
        >>> repeater == {
2308
 
        ...     'dogs': {'dog1': {}, 'dog2': {}, 'dog3': {}},
2309
 
        ...     'cats': {'cat1': {}, 'cat2': {}, 'cat3': {}},
2310
 
        ... }
2311
 
        1
2312
 
        >>> repeater.validate(val)
2313
 
        1
2314
 
        >>> repeater == {
2315
 
        ...     'dogs': {'dog1': {}, 'dog2': {}, 'dog3': {}},
2316
 
        ...     'cats': {
2317
 
        ...         'cat1': {
2318
 
        ...             'fleas': True,
2319
 
        ...             'tail': 'short',
2320
 
        ...             'name': 'pussy',
2321
 
        ...             'description': {
2322
 
        ...                 'weight': 6.0,
2323
 
        ...                 'height': 3.2999999999999998,
2324
 
        ...                 'coat': {'fur': 'black', 'condition': 5},
2325
 
        ...             },
2326
 
        ...         },
2327
 
        ...         'cat2': {
2328
 
        ...             'fleas': True,
2329
 
        ...             'tail': 'short',
2330
 
        ...             'name': 'pussy',
2331
 
        ...             'description': {
2332
 
        ...                 'weight': 6.0,
2333
 
        ...                 'height': 3.2999999999999998,
2334
 
        ...                 'coat': {'fur': 'black', 'condition': 5},
2335
 
        ...             },
2336
 
        ...         },
2337
 
        ...         'cat3': {
2338
 
        ...             'fleas': True,
2339
 
        ...             'tail': 'short',
2340
 
        ...             'name': 'pussy',
2341
 
        ...             'description': {
2342
 
        ...                 'weight': 6.0,
2343
 
        ...                 'height': 3.2999999999999998,
2344
 
        ...                 'coat': {'fur': 'black', 'condition': 5},
2345
 
        ...             },
2346
 
        ...         },
2347
 
        ...     },
2348
 
        ... }
2349
 
        1
2350
 
        
2351
 
        Test that interpolation is preserved for validated string values.
2352
 
        Also check that interpolation works in configspecs.
2353
 
        >>> t = ConfigObj()
2354
 
        >>> t['DEFAULT'] = {}
2355
 
        >>> t['DEFAULT']['test'] = 'a'
2356
 
        >>> t['test'] = '%(test)s'
2357
 
        >>> t['test']
2358
 
        'a'
2359
 
        >>> v = Validator()
2360
 
        >>> t.configspec = {'test': 'string'}
2361
 
        >>> t.validate(v)
2362
 
        1
2363
 
        >>> t.interpolation = False
2364
 
        >>> t
2365
 
        {'test': '%(test)s', 'DEFAULT': {'test': 'a'}}
2366
 
        >>> specs = [
2367
 
        ...    'interpolated string  = string(default="fuzzy-%(man)s")',
2368
 
        ...    '[DEFAULT]',
2369
 
        ...    'man = wuzzy',
2370
 
        ...    ]
2371
 
        >>> c = ConfigObj(configspec=specs)
2372
 
        >>> c.validate(v)
2373
 
        1
2374
 
        >>> c['interpolated string']
2375
 
        'fuzzy-wuzzy'
2376
 
        
2377
 
        FIXME: Above tests will fail if we couldn't import Validator (the ones
2378
 
        that don't raise errors will produce different output and still fail as
2379
 
        tests)
2380
2112
        """
2381
2113
        if section is None:
2382
2114
            if self.configspec is None:
2383
 
                raise ValueError, 'No configspec supplied.'
 
2115
                raise ValueError('No configspec supplied.')
2384
2116
            if preserve_errors:
2385
 
                if VdtMissingValue is None:
2386
 
                    raise ImportError('Missing validate module.')
 
2117
                # We do this once to remove a top level dependency on the validate module
 
2118
                # Which makes importing configobj faster
 
2119
                from validate import VdtMissingValue
 
2120
                self._vdtMissingValue = VdtMissingValue
 
2121
 
2387
2122
            section = self
2388
 
        #
2389
 
        spec_section = section.configspec
2390
 
        if '__many__' in section.configspec:
2391
 
            many = spec_section['__many__']
2392
 
            # dynamically assign the configspecs
2393
 
            # for the sections below
2394
 
            for entry in section.sections:
2395
 
                self._handle_repeat(section[entry], many)
2396
 
        #
2397
 
        out = {}
2398
 
        ret_true = True
2399
 
        ret_false = True
2400
 
        for entry in spec_section:
2401
 
            if entry == '__many__':
2402
 
                continue
2403
 
            if (not entry in section.scalars) or (entry in section.defaults):
2404
 
                # missing entries
2405
 
                # or entries from defaults
2406
 
                missing = True
2407
 
                val = None
2408
 
            else:
2409
 
                missing = False
2410
 
                val = section[entry]
 
2123
 
 
2124
            if copy:
 
2125
                section.initial_comment = section.configspec.initial_comment
 
2126
                section.final_comment = section.configspec.final_comment
 
2127
                section.encoding = section.configspec.encoding
 
2128
                section.BOM = section.configspec.BOM
 
2129
                section.newlines = section.configspec.newlines
 
2130
                section.indent_type = section.configspec.indent_type
 
2131
 
 
2132
        #
 
2133
        configspec = section.configspec
 
2134
        self._set_configspec(section, copy)
 
2135
 
 
2136
        def validate_entry(entry, spec, val, missing, ret_true, ret_false):
2411
2137
            try:
2412
 
                check = validator.check(spec_section[entry],
 
2138
                check = validator.check(spec,
2413
2139
                                        val,
2414
2140
                                        missing=missing
2415
2141
                                        )
2416
2142
            except validator.baseErrorClass, e:
2417
 
                if not preserve_errors or isinstance(e, VdtMissingValue):
 
2143
                if not preserve_errors or isinstance(e, self._vdtMissingValue):
2418
2144
                    out[entry] = False
2419
2145
                else:
2420
2146
                    # preserve the error
2422
2148
                    ret_false = False
2423
2149
                ret_true = False
2424
2150
            else:
 
2151
                try:
 
2152
                    section.default_values.pop(entry, None)
 
2153
                except AttributeError:
 
2154
                    # For Python 2.2 compatibility
 
2155
                    try:
 
2156
                        del section.default_values[entry]
 
2157
                    except KeyError:
 
2158
                        pass
 
2159
 
 
2160
                try:
 
2161
                    section.default_values[entry] = validator.get_default_value(configspec[entry])
 
2162
                except (KeyError, AttributeError):
 
2163
                    # No default or validator has no 'get_default_value' (e.g. SimpleVal)
 
2164
                    pass
 
2165
 
2425
2166
                ret_false = False
2426
2167
                out[entry] = True
2427
2168
                if self.stringify or missing:
2438
2179
                            check = self._str(check)
2439
2180
                    if (check != val) or missing:
2440
2181
                        section[entry] = check
2441
 
                if missing and entry not in section.defaults:
 
2182
                if not copy and missing and entry not in section.defaults:
2442
2183
                    section.defaults.append(entry)
 
2184
            return ret_true, ret_false
 
2185
 
2443
2186
        #
2444
 
        # FIXME: Will this miss missing sections ?
 
2187
        out = {}
 
2188
        ret_true = True
 
2189
        ret_false = True
 
2190
 
 
2191
        unvalidated = [k for k in section.scalars if k not in configspec]
 
2192
        incorrect_sections = [k for k in configspec.sections if k in section.scalars]
 
2193
        incorrect_scalars = [k for k in configspec.scalars if k in section.sections]
 
2194
 
 
2195
        for entry in configspec.scalars:
 
2196
            if entry in ('__many__', '___many___'):
 
2197
                # reserved names
 
2198
                continue
 
2199
 
 
2200
            if (not entry in section.scalars) or (entry in section.defaults):
 
2201
                # missing entries
 
2202
                # or entries from defaults
 
2203
                missing = True
 
2204
                val = None
 
2205
                if copy and not entry in section.scalars:
 
2206
                    # copy comments
 
2207
                    section.comments[entry] = (
 
2208
                        configspec.comments.get(entry, []))
 
2209
                    section.inline_comments[entry] = (
 
2210
                        configspec.inline_comments.get(entry, ''))
 
2211
                #
 
2212
            else:
 
2213
                missing = False
 
2214
                val = section[entry]
 
2215
 
 
2216
            ret_true, ret_false = validate_entry(entry, configspec[entry], val,
 
2217
                                                 missing, ret_true, ret_false)
 
2218
 
 
2219
        many = None
 
2220
        if '__many__' in configspec.scalars:
 
2221
            many = configspec['__many__']
 
2222
        elif '___many___' in configspec.scalars:
 
2223
            many = configspec['___many___']
 
2224
 
 
2225
        if many is not None:
 
2226
            for entry in unvalidated:
 
2227
                val = section[entry]
 
2228
                ret_true, ret_false = validate_entry(entry, many, val, False,
 
2229
                                                     ret_true, ret_false)
 
2230
 
 
2231
        for entry in incorrect_scalars:
 
2232
            ret_true = False
 
2233
            if not preserve_errors:
 
2234
                out[entry] = False
 
2235
            else:
 
2236
                ret_false = False
 
2237
                msg = 'Value %r was provided as a section' % entry
 
2238
                out[entry] = validator.baseErrorClass(msg)
 
2239
        for entry in incorrect_sections:
 
2240
            ret_true = False
 
2241
            if not preserve_errors:
 
2242
                out[entry] = False
 
2243
            else:
 
2244
                ret_false = False
 
2245
                msg = 'Section %r was provided as a single value' % entry
 
2246
                out[entry] = validator.baseErrorClass(msg)
 
2247
 
 
2248
        # Missing sections will have been created as empty ones when the
 
2249
        # configspec was read.
2445
2250
        for entry in section.sections:
 
2251
            # FIXME: this means DEFAULT is not copied in copy mode
2446
2252
            if section is self and entry == 'DEFAULT':
2447
2253
                continue
2448
 
            check = self.validate(validator, preserve_errors=preserve_errors,
2449
 
                section=section[entry])
 
2254
            if section[entry].configspec is None:
 
2255
                continue
 
2256
            if copy:
 
2257
                section.comments[entry] = configspec.comments.get(entry, [])
 
2258
                section.inline_comments[entry] = configspec.inline_comments.get(entry, '')
 
2259
            check = self.validate(validator, preserve_errors=preserve_errors, copy=copy, section=section[entry])
2450
2260
            out[entry] = check
2451
2261
            if check == False:
2452
2262
                ret_true = False
2460
2270
            return True
2461
2271
        elif ret_false:
2462
2272
            return False
2463
 
        else:
2464
 
            return out
 
2273
        return out
 
2274
 
 
2275
 
 
2276
    def reset(self):
 
2277
        """Clear ConfigObj instance and restore to 'freshly created' state."""
 
2278
        self.clear()
 
2279
        self._initialise()
 
2280
        # FIXME: Should be done by '_initialise', but ConfigObj constructor (and reload)
 
2281
        #        requires an empty dictionary
 
2282
        self.configspec = None
 
2283
        # Just to be sure ;-)
 
2284
        self._original_configspec = None
 
2285
 
 
2286
 
 
2287
    def reload(self):
 
2288
        """
 
2289
        Reload a ConfigObj from file.
 
2290
 
 
2291
        This method raises a ``ReloadError`` if the ConfigObj doesn't have
 
2292
        a filename attribute pointing to a file.
 
2293
        """
 
2294
        if not isinstance(self.filename, basestring):
 
2295
            raise ReloadError()
 
2296
 
 
2297
        filename = self.filename
 
2298
        current_options = {}
 
2299
        for entry in OPTION_DEFAULTS:
 
2300
            if entry == 'configspec':
 
2301
                continue
 
2302
            current_options[entry] = getattr(self, entry)
 
2303
 
 
2304
        configspec = self._original_configspec
 
2305
        current_options['configspec'] = configspec
 
2306
 
 
2307
        self.clear()
 
2308
        self._initialise(current_options)
 
2309
        self._load(filename, configspec)
 
2310
 
 
2311
 
2465
2312
 
2466
2313
class SimpleVal(object):
2467
2314
    """
2468
2315
    A simple validator.
2469
2316
    Can be used to check that all members expected are present.
2470
 
    
 
2317
 
2471
2318
    To use it, provide a configspec with all your members in (the value given
2472
2319
    will be ignored). Pass an instance of ``SimpleVal`` to the ``validate``
2473
2320
    method of your ``ConfigObj``. ``validate`` will return ``True`` if all
2474
2321
    members are present, or a dictionary with True/False meaning
2475
2322
    present/missing. (Whole missing sections will be replaced with ``False``)
2476
 
    
2477
 
    >>> val = SimpleVal()
2478
 
    >>> config = '''
2479
 
    ... test1=40
2480
 
    ... test2=hello
2481
 
    ... test3=3
2482
 
    ... test4=5.0
2483
 
    ... [section]
2484
 
    ... test1=40
2485
 
    ... test2=hello
2486
 
    ... test3=3
2487
 
    ... test4=5.0
2488
 
    ...     [[sub section]]
2489
 
    ...     test1=40
2490
 
    ...     test2=hello
2491
 
    ...     test3=3
2492
 
    ...     test4=5.0
2493
 
    ... '''.split('\\n')
2494
 
    >>> configspec = '''
2495
 
    ... test1=''
2496
 
    ... test2=''
2497
 
    ... test3=''
2498
 
    ... test4=''
2499
 
    ... [section]
2500
 
    ... test1=''
2501
 
    ... test2=''
2502
 
    ... test3=''
2503
 
    ... test4=''
2504
 
    ...     [[sub section]]
2505
 
    ...     test1=''
2506
 
    ...     test2=''
2507
 
    ...     test3=''
2508
 
    ...     test4=''
2509
 
    ... '''.split('\\n')
2510
 
    >>> o = ConfigObj(config, configspec=configspec)
2511
 
    >>> o.validate(val)
2512
 
    1
2513
 
    >>> o = ConfigObj(configspec=configspec)
2514
 
    >>> o.validate(val)
2515
 
    0
2516
2323
    """
2517
 
    
 
2324
 
2518
2325
    def __init__(self):
2519
2326
        self.baseErrorClass = ConfigObjError
2520
 
    
 
2327
 
2521
2328
    def check(self, check, member, missing=False):
2522
2329
        """A dummy check method, always returns the value unchanged."""
2523
2330
        if missing:
2524
 
            raise self.baseErrorClass
 
2331
            raise self.baseErrorClass()
2525
2332
        return member
2526
2333
 
 
2334
 
2527
2335
# Check / processing functions for options
2528
2336
def flatten_errors(cfg, res, levels=None, results=None):
2529
2337
    """
2530
2338
    An example function that will turn a nested dictionary of results
2531
2339
    (as returned by ``ConfigObj.validate``) into a flat list.
2532
 
    
 
2340
 
2533
2341
    ``cfg`` is the ConfigObj instance being checked, ``res`` is the results
2534
2342
    dictionary returned by ``validate``.
2535
 
    
 
2343
 
2536
2344
    (This is a recursive function, so you shouldn't use the ``levels`` or
2537
 
    ``results`` arguments - they are used by the function.
2538
 
    
 
2345
    ``results`` arguments - they are used by the function.)
 
2346
 
2539
2347
    Returns a list of keys that failed. Each member of the list is a tuple :
 
2348
 
2540
2349
    ::
2541
 
    
 
2350
 
2542
2351
        ([list of sections...], key, result)
2543
 
    
 
2352
 
2544
2353
    If ``validate`` was called with ``preserve_errors=False`` (the default)
2545
2354
    then ``result`` will always be ``False``.
2546
2355
 
2547
2356
    *list of sections* is a flattened list of sections that the key was found
2548
2357
    in.
2549
 
    
2550
 
    If the section was missing then key will be ``None``.
2551
 
    
 
2358
 
 
2359
    If the section was missing (or a section was expected and a scalar provided
 
2360
    - or vice-versa) then key will be ``None``.
 
2361
 
2552
2362
    If the value (or section) was missing then ``result`` will be ``False``.
2553
 
    
 
2363
 
2554
2364
    If ``validate`` was called with ``preserve_errors=True`` and a value
2555
2365
    was present, but failed the check, then ``result`` will be the exception
2556
2366
    object returned. You can use this as a string that describes the failure.
2557
 
    
 
2367
 
2558
2368
    For example *The value "3" is of the wrong type*.
2559
 
    
2560
 
    # FIXME: is the ordering of the output arbitrary ?
 
2369
 
2561
2370
    >>> import validate
2562
2371
    >>> vtor = validate.Validator()
2563
2372
    >>> my_ini = '''
2627
2436
        results = []
2628
2437
    if res is True:
2629
2438
        return results
2630
 
    if res is False:
2631
 
        results.append((levels[:], None, False))
 
2439
    if res is False or isinstance(res, Exception):
 
2440
        results.append((levels[:], None, res))
2632
2441
        if levels:
2633
2442
            levels.pop()
2634
2443
        return results
2649
2458
    return results
2650
2459
 
2651
2460
 
2652
 
# FIXME: test error code for badly built multiline values
2653
 
# FIXME: test handling of StringIO
2654
 
# FIXME: test interpolation with writing
2655
 
 
2656
 
def _doctest():
2657
 
    """
2658
 
    Dummy function to hold some of the doctests.
2659
 
    
2660
 
    >>> a.depth
2661
 
    0
2662
 
    >>> a == {
2663
 
    ...     'key2': 'val',
2664
 
    ...     'key1': 'val',
2665
 
    ...     'lev1c': {
2666
 
    ...         'lev2c': {
2667
 
    ...             'lev3c': {
2668
 
    ...                 'key1': 'val',
2669
 
    ...             },
2670
 
    ...         },
2671
 
    ...     },
2672
 
    ...     'lev1b': {
2673
 
    ...         'key2': 'val',
2674
 
    ...         'key1': 'val',
2675
 
    ...         'lev2ba': {
2676
 
    ...             'key1': 'val',
2677
 
    ...         },
2678
 
    ...         'lev2bb': {
2679
 
    ...             'key1': 'val',
2680
 
    ...         },
2681
 
    ...     },
2682
 
    ...     'lev1a': {
2683
 
    ...         'key2': 'val',
2684
 
    ...         'key1': 'val',
2685
 
    ...     },
2686
 
    ... }
2687
 
    1
2688
 
    >>> b.depth
2689
 
    0
2690
 
    >>> b == {
2691
 
    ...     'key3': 'val3',
2692
 
    ...     'key2': 'val2',
2693
 
    ...     'key1': 'val1',
2694
 
    ...     'section 1': {
2695
 
    ...         'keys11': 'val1',
2696
 
    ...         'keys13': 'val3',
2697
 
    ...         'keys12': 'val2',
2698
 
    ...     },
2699
 
    ...     'section 2': {
2700
 
    ...         'section 2 sub 1': {
2701
 
    ...             'fish': '3',
2702
 
    ...     },
2703
 
    ...     'keys21': 'val1',
2704
 
    ...     'keys22': 'val2',
2705
 
    ...     'keys23': 'val3',
2706
 
    ...     },
2707
 
    ... }
2708
 
    1
2709
 
    >>> t = '''
2710
 
    ... 'a' = b # !"$%^&*(),::;'@~#= 33
2711
 
    ... "b" = b #= 6, 33
2712
 
    ... ''' .split('\\n')
2713
 
    >>> t2 = ConfigObj(t)
2714
 
    >>> assert t2 == {'a': 'b', 'b': 'b'}
2715
 
    >>> t2.inline_comments['b'] = ''
2716
 
    >>> del t2['a']
2717
 
    >>> assert t2.write() == ['','b = b', '']
2718
 
    
2719
 
    # Test ``list_values=False`` stuff
2720
 
    >>> c = '''
2721
 
    ...     key1 = no quotes
2722
 
    ...     key2 = 'single quotes'
2723
 
    ...     key3 = "double quotes"
2724
 
    ...     key4 = "list", 'with', several, "quotes"
2725
 
    ...     '''
2726
 
    >>> cfg = ConfigObj(c.splitlines(), list_values=False)
2727
 
    >>> cfg == {'key1': 'no quotes', 'key2': "'single quotes'", 
2728
 
    ... 'key3': '"double quotes"', 
2729
 
    ... 'key4': '"list", \\'with\\', several, "quotes"'
2730
 
    ... }
2731
 
    1
2732
 
    >>> cfg = ConfigObj(list_values=False)
2733
 
    >>> cfg['key1'] = 'Multiline\\nValue'
2734
 
    >>> cfg['key2'] = '''"Value" with 'quotes' !'''
2735
 
    >>> cfg.write()
2736
 
    ["key1 = '''Multiline\\nValue'''", 'key2 = "Value" with \\'quotes\\' !']
2737
 
    >>> cfg.list_values = True
2738
 
    >>> cfg.write() == ["key1 = '''Multiline\\nValue'''",
2739
 
    ... 'key2 = \\'\\'\\'"Value" with \\'quotes\\' !\\'\\'\\'']
2740
 
    1
2741
 
    
2742
 
    Test flatten_errors:
2743
 
    
2744
 
    >>> from validate import Validator, VdtValueTooSmallError
2745
 
    >>> config = '''
2746
 
    ...     test1=40
2747
 
    ...     test2=hello
2748
 
    ...     test3=3
2749
 
    ...     test4=5.0
2750
 
    ...     [section]
2751
 
    ...         test1=40
2752
 
    ...         test2=hello
2753
 
    ...         test3=3
2754
 
    ...         test4=5.0
2755
 
    ...         [[sub section]]
2756
 
    ...             test1=40
2757
 
    ...             test2=hello
2758
 
    ...             test3=3
2759
 
    ...             test4=5.0
2760
 
    ... '''.split('\\n')
2761
 
    >>> configspec = '''
2762
 
    ...     test1= integer(30,50)
2763
 
    ...     test2= string
2764
 
    ...     test3=integer
2765
 
    ...     test4=float(6.0)
2766
 
    ...     [section ]
2767
 
    ...         test1=integer(30,50)
2768
 
    ...         test2=string
2769
 
    ...         test3=integer
2770
 
    ...         test4=float(6.0)
2771
 
    ...         [[sub section]]
2772
 
    ...             test1=integer(30,50)
2773
 
    ...             test2=string
2774
 
    ...             test3=integer
2775
 
    ...             test4=float(6.0)
2776
 
    ...     '''.split('\\n')
2777
 
    >>> val = Validator()
2778
 
    >>> c1 = ConfigObj(config, configspec=configspec)
2779
 
    >>> res = c1.validate(val)
2780
 
    >>> flatten_errors(c1, res) == [([], 'test4', False), (['section', 
2781
 
    ...     'sub section'], 'test4', False), (['section'], 'test4', False)]
2782
 
    True
2783
 
    >>> res = c1.validate(val, preserve_errors=True)
2784
 
    >>> check = flatten_errors(c1, res)
2785
 
    >>> check[0][:2]
2786
 
    ([], 'test4')
2787
 
    >>> check[1][:2]
2788
 
    (['section', 'sub section'], 'test4')
2789
 
    >>> check[2][:2]
2790
 
    (['section'], 'test4')
2791
 
    >>> for entry in check:
2792
 
    ...     isinstance(entry[2], VdtValueTooSmallError)
2793
 
    ...     print str(entry[2])
2794
 
    True
2795
 
    the value "5.0" is too small.
2796
 
    True
2797
 
    the value "5.0" is too small.
2798
 
    True
2799
 
    the value "5.0" is too small.
2800
 
    
2801
 
    Test unicode handling, BOM, write witha file like object and line endings :
2802
 
    >>> u_base = '''
2803
 
    ... # initial comment
2804
 
    ...     # inital comment 2
2805
 
    ... 
2806
 
    ... test1 = some value
2807
 
    ... # comment
2808
 
    ... test2 = another value    # inline comment
2809
 
    ... # section comment
2810
 
    ... [section]    # inline comment
2811
 
    ...     test = test    # another inline comment
2812
 
    ...     test2 = test2
2813
 
    ... 
2814
 
    ... # final comment
2815
 
    ... # final comment2
2816
 
    ... '''
2817
 
    >>> u = u_base.encode('utf_8').splitlines(True)
2818
 
    >>> u[0] = BOM_UTF8 + u[0]
2819
 
    >>> uc = ConfigObj(u)
2820
 
    >>> uc.encoding = None
2821
 
    >>> uc.BOM == True
2822
 
    1
2823
 
    >>> uc == {'test1': 'some value', 'test2': 'another value',
2824
 
    ... 'section': {'test': 'test', 'test2': 'test2'}}
2825
 
    1
2826
 
    >>> uc = ConfigObj(u, encoding='utf_8', default_encoding='latin-1')
2827
 
    >>> uc.BOM
2828
 
    1
2829
 
    >>> isinstance(uc['test1'], unicode)
2830
 
    1
2831
 
    >>> uc.encoding
2832
 
    'utf_8'
2833
 
    >>> uc.newlines
2834
 
    '\\n'
2835
 
    >>> uc['latin1'] = "This costs lot's of "
2836
 
    >>> a_list = uc.write()
2837
 
    >>> len(a_list)
2838
 
    15
2839
 
    >>> isinstance(a_list[0], str)
2840
 
    1
2841
 
    >>> a_list[0].startswith(BOM_UTF8)
2842
 
    1
2843
 
    >>> u = u_base.replace('\\n', '\\r\\n').encode('utf_8').splitlines(True)
2844
 
    >>> uc = ConfigObj(u)
2845
 
    >>> uc.newlines
2846
 
    '\\r\\n'
2847
 
    >>> uc.newlines = '\\r'
2848
 
    >>> from cStringIO import StringIO
2849
 
    >>> file_like = StringIO()
2850
 
    >>> uc.write(file_like)
2851
 
    >>> file_like.seek(0)
2852
 
    >>> uc2 = ConfigObj(file_like)
2853
 
    >>> uc2 == uc
2854
 
    1
2855
 
    >>> uc2.filename is None
2856
 
    1
2857
 
    >>> uc2.newlines == '\\r'
2858
 
    1
2859
 
    """
2860
 
 
2861
 
if __name__ == '__main__':
2862
 
    # run the code tests in doctest format
2863
 
    #
2864
 
    testconfig1 = """\
2865
 
    key1= val    # comment 1
2866
 
    key2= val    # comment 2
2867
 
    # comment 3
2868
 
    [lev1a]     # comment 4
2869
 
    key1= val    # comment 5
2870
 
    key2= val    # comment 6
2871
 
    # comment 7
2872
 
    [lev1b]    # comment 8
2873
 
    key1= val    # comment 9
2874
 
    key2= val    # comment 10
2875
 
    # comment 11
2876
 
        [[lev2ba]]    # comment 12
2877
 
        key1= val    # comment 13
2878
 
        # comment 14
2879
 
        [[lev2bb]]    # comment 15
2880
 
        key1= val    # comment 16
2881
 
    # comment 17
2882
 
    [lev1c]    # comment 18
2883
 
    # comment 19
2884
 
        [[lev2c]]    # comment 20
2885
 
        # comment 21
2886
 
            [[[lev3c]]]    # comment 22
2887
 
            key1 = val    # comment 23"""
2888
 
    #
2889
 
    testconfig2 = """\
2890
 
                        key1 = 'val1'
2891
 
                        key2 =   "val2"
2892
 
                        key3 = val3
2893
 
                        ["section 1"] # comment
2894
 
                        keys11 = val1
2895
 
                        keys12 = val2
2896
 
                        keys13 = val3
2897
 
                        [section 2]
2898
 
                        keys21 = val1
2899
 
                        keys22 = val2
2900
 
                        keys23 = val3
2901
 
                        
2902
 
                            [['section 2 sub 1']]
2903
 
                            fish = 3
2904
 
    """
2905
 
    #
2906
 
    testconfig6 = '''
2907
 
    name1 = """ a single line value """ # comment
2908
 
    name2 = \''' another single line value \''' # comment
2909
 
    name3 = """ a single line value """
2910
 
    name4 = \''' another single line value \'''
2911
 
        [ "multi section" ]
2912
 
        name1 = """
2913
 
        Well, this is a
2914
 
        multiline value
2915
 
        """
2916
 
        name2 = \'''
2917
 
        Well, this is a
2918
 
        multiline value
2919
 
        \'''
2920
 
        name3 = """
2921
 
        Well, this is a
2922
 
        multiline value
2923
 
        """     # a comment
2924
 
        name4 = \'''
2925
 
        Well, this is a
2926
 
        multiline value
2927
 
        \'''  # I guess this is a comment too
2928
 
    '''
2929
 
    #
2930
 
    import doctest
2931
 
    m = sys.modules.get('__main__')
2932
 
    globs = m.__dict__.copy()
2933
 
    a = ConfigObj(testconfig1.split('\n'), raise_errors=True)
2934
 
    b = ConfigObj(testconfig2.split('\n'), raise_errors=True)
2935
 
    i = ConfigObj(testconfig6.split('\n'), raise_errors=True)
2936
 
    globs.update({
2937
 
        'INTP_VER': INTP_VER,
2938
 
        'a': a,
2939
 
        'b': b,
2940
 
        'i': i,
2941
 
    })
2942
 
    doctest.testmod(m, globs=globs)
2943
 
 
2944
 
"""
2945
 
    BUGS
2946
 
    ====
2947
 
    
2948
 
    None known.
2949
 
    
2950
 
    TODO
2951
 
    ====
2952
 
    
2953
 
    Better support for configuration from multiple files, including tracking
2954
 
    *where* the original file came from and writing changes to the correct
2955
 
    file.
2956
 
    
2957
 
    
2958
 
    Make ``newline`` an option (as well as an attribute) ?
2959
 
    
2960
 
    ``UTF16`` encoded files, when returned as a list of lines, will have the
2961
 
    BOM at the start of every line. Should this be removed from all but the
2962
 
    first line ?
2963
 
    
2964
 
    Option to set warning type for unicode decode ? (Defaults to strict).
2965
 
    
2966
 
    A method to optionally remove uniform indentation from multiline values.
2967
 
    (do as an example of using ``walk`` - along with string-escape)
2968
 
    
2969
 
    Should the results dictionary from validate be an ordered dictionary if
2970
 
    `odict <http://www.voidspace.org.uk/python/odict.html>`_ is available ?
2971
 
    
2972
 
    Implement a better ``__repr__`` ? (``ConfigObj({})``)
2973
 
    
2974
 
    Implement some of the sequence methods (which include slicing) from the
2975
 
    newer ``odict`` ?
2976
 
    
2977
 
    INCOMPATIBLE CHANGES
2978
 
    ====================
2979
 
    
2980
 
    (I have removed a lot of needless complications - this list is probably not
2981
 
    conclusive, many option/attribute/method names have changed)
2982
 
    
2983
 
    Case sensitive
2984
 
    
2985
 
    The only valid divider is '='
2986
 
    
2987
 
    We've removed line continuations with '\'
2988
 
    
2989
 
    No recursive lists in values
2990
 
    
2991
 
    No empty section
2992
 
    
2993
 
    No distinction between flatfiles and non flatfiles
2994
 
    
2995
 
    Change in list syntax - use commas to indicate list, not parentheses
2996
 
    (square brackets and parentheses are no longer recognised as lists)
2997
 
    
2998
 
    ';' is no longer valid for comments and no multiline comments
2999
 
    
3000
 
    No attribute access
3001
 
    
3002
 
    We don't allow empty values - have to use '' or ""
3003
 
    
3004
 
    In ConfigObj 3 - setting a non-flatfile member to ``None`` would
3005
 
    initialise it as an empty section.
3006
 
    
3007
 
    The escape entities '&mjf-lf;' and '&mjf-quot;' have gone
3008
 
    replaced by triple quote, multiple line values.
3009
 
    
3010
 
    The ``newline``, ``force_return``, and ``default`` options have gone
3011
 
    
3012
 
    The ``encoding`` and ``backup_encoding`` methods have gone - replaced
3013
 
    with the ``encode`` and ``decode`` methods.
3014
 
    
3015
 
    ``fileerror`` and ``createempty`` options have become ``file_error`` and
3016
 
    ``create_empty``
3017
 
    
3018
 
    Partial configspecs (for specifying the order members should be written
3019
 
    out and which should be present) have gone. The configspec is no longer
3020
 
    used to specify order for the ``write`` method.
3021
 
    
3022
 
    Exceeding the maximum depth of recursion in string interpolation now
3023
 
    raises an error ``InterpolationDepthError``.
3024
 
    
3025
 
    Specifying a value for interpolation which doesn't exist now raises an
3026
 
    error ``MissingInterpolationOption`` (instead of merely being ignored).
3027
 
    
3028
 
    The ``writein`` method has been removed.
3029
 
    
3030
 
    The comments attribute is now a list (``inline_comments`` equates to the
3031
 
    old comments attribute)
3032
 
    
3033
 
    ISSUES
3034
 
    ======
3035
 
    
3036
 
    ``validate`` doesn't report *extra* values or sections.
3037
 
    
3038
 
    You can't have a keyword with the same name as a section (in the same
3039
 
    section). They are both dictionary keys - so they would overlap.
3040
 
    
3041
 
    ConfigObj doesn't quote and unquote values if ``list_values=False``.
3042
 
    This means that leading or trailing whitespace in values will be lost when
3043
 
    writing. (Unless you manually quote).
3044
 
    
3045
 
    Interpolation checks first the 'DEFAULT' subsection of the current
3046
 
    section, next it checks the 'DEFAULT' section of the parent section,
3047
 
    last it checks the 'DEFAULT' section of the main section.
3048
 
    
3049
 
    Logically a 'DEFAULT' section should apply to all subsections of the *same
3050
 
    parent* - this means that checking the 'DEFAULT' subsection in the
3051
 
    *current section* is not necessarily logical ?
3052
 
    
3053
 
    In order to simplify unicode support (which is possibly of limited value
3054
 
    in a config file) I have removed automatic support and added the
3055
 
    ``encode`` and ``decode methods, which can be used to transform keys and
3056
 
    entries. Because the regex looks for specific values on inital parsing
3057
 
    (i.e. the quotes and the equals signs) it can only read ascii compatible
3058
 
    encodings. For unicode use ``UTF8``, which is ASCII compatible.
3059
 
    
3060
 
    Does it matter that we don't support the ':' divider, which is supported
3061
 
    by ``ConfigParser`` ?
3062
 
    
3063
 
    The regular expression correctly removes the value -
3064
 
    ``"'hello', 'goodbye'"`` and then unquote just removes the front and
3065
 
    back quotes (called from ``_handle_value``). What should we do ??
3066
 
    (*ought* to raise exception because it's an invalid value if lists are
3067
 
    off *sigh*. This is not what you want if you want to do your own list
3068
 
    processing - would be *better* in this case not to unquote.)
3069
 
    
3070
 
    String interpolation and validation don't play well together. When
3071
 
    validation changes type it sets the value. This will correctly fetch the
3072
 
    value using interpolation - but then overwrite the interpolation reference.
3073
 
    If the value is unchanged by validation (it's a string) - but other types
3074
 
    will be.
3075
 
    
3076
 
    
3077
 
    List Value Syntax
3078
 
    =================
3079
 
    
3080
 
    List values allow you to specify multiple values for a keyword. This
3081
 
    maps to a list as the resulting Python object when parsed.
3082
 
    
3083
 
    The syntax for lists is easy. A list is a comma separated set of values.
3084
 
    If these values contain quotes, the hash mark, or commas, then the values
3085
 
    can be surrounded by quotes. e.g. : ::
3086
 
    
3087
 
        keyword = value1, 'value 2', "value 3"
3088
 
    
3089
 
    If a value needs to be a list, but only has one member, then you indicate
3090
 
    this with a trailing comma. e.g. : ::
3091
 
    
3092
 
        keyword = "single value",
3093
 
    
3094
 
    If a value needs to be a list, but it has no members, then you indicate
3095
 
    this with a single comma. e.g. : ::
3096
 
    
3097
 
        keyword = ,     # an empty list
3098
 
    
3099
 
    Using triple quotes it will be possible for single values to contain
3100
 
    newlines and *both* single quotes and double quotes. Triple quotes aren't
3101
 
    allowed in list values. This means that the members of list values can't
3102
 
    contain carriage returns (or line feeds :-) or both quote values.
3103
 
      
3104
 
    CHANGELOG
3105
 
    =========
3106
 
    
3107
 
    2006/02/04
3108
 
    ----------
3109
 
    
3110
 
    Removed ``BOM_UTF8`` from ``__all__``.
3111
 
    
3112
 
    The ``BOM`` attribute has become a boolean. (Defaults to ``False``.) It is
3113
 
    *only* ``True`` for the ``UTF16`` encoding.
3114
 
    
3115
 
    File like objects no longer need a ``seek`` attribute.
3116
 
    
3117
 
    ConfigObj no longer keeps a reference to file like objects. Instead the
3118
 
    ``write`` method takes a file like object as an optional argument. (Which
3119
 
    will be used in preference of the ``filename`` attribute if htat exists as
3120
 
    well.)
3121
 
    
3122
 
    Full unicode support added. New options/attributes ``encoding``,
3123
 
    ``default_encoding``.
3124
 
    
3125
 
    utf16 files decoded to unicode.
3126
 
    
3127
 
    If ``BOM`` is ``True``, but no encoding specified, then the utf8 BOM is
3128
 
    written out at the start of the file. (It will normally only be ``True`` if
3129
 
    the utf8 BOM was found when the file was read.)
3130
 
    
3131
 
    File paths are *not* converted to absolute paths, relative paths will
3132
 
    remain relative as the ``filename`` attribute.
3133
 
    
3134
 
    Fixed bug where ``final_comment`` wasn't returned if ``write`` is returning
3135
 
    a list of lines.
3136
 
    
3137
 
    2006/01/31
3138
 
    ----------
3139
 
    
3140
 
    Added ``True``, ``False``, and ``enumerate`` if they are not defined.
3141
 
    (``True`` and ``False`` are needed for *early* versions of Python 2.2,
3142
 
    ``enumerate`` is needed for all versions ofPython 2.2)
3143
 
    
3144
 
    Deprecated ``istrue``, replaced it with ``as_bool``.
3145
 
    
3146
 
    Added ``as_int`` and ``as_float``.
3147
 
    
3148
 
    utf8 and utf16 BOM handled in an endian agnostic way.
3149
 
    
3150
 
    2005/12/14
3151
 
    ----------
3152
 
    
3153
 
    Validation no longer done on the 'DEFAULT' section (only in the root
3154
 
    level). This allows interpolation in configspecs.
3155
 
    
3156
 
    Change in validation syntax implemented in validate 0.2.1
3157
 
    
3158
 
    4.1.0
3159
 
    
3160
 
    2005/12/10
3161
 
    ----------
3162
 
    
3163
 
    Added ``merge``, a recursive update.
3164
 
    
3165
 
    Added ``preserve_errors`` to ``validate`` and the ``flatten_errors``
3166
 
    example function.
3167
 
    
3168
 
    Thanks to Matthew Brett for suggestions and helping me iron out bugs.
3169
 
    
3170
 
    Fixed bug where a config file is *all* comment, the comment will now be
3171
 
    ``initial_comment`` rather than ``final_comment``.
3172
 
    
3173
 
    2005/12/02
3174
 
    ----------
3175
 
    
3176
 
    Fixed bug in ``create_empty``. Thanks to Paul Jimenez for the report.
3177
 
    
3178
 
    2005/11/04
3179
 
    ----------
3180
 
    
3181
 
    Fixed bug in ``Section.walk`` when transforming names as well as values.
3182
 
    
3183
 
    Added the ``istrue`` method. (Fetches the boolean equivalent of a string
3184
 
    value).
3185
 
    
3186
 
    Fixed ``list_values=False`` - they are now only quoted/unquoted if they
3187
 
    are multiline values.
3188
 
    
3189
 
    List values are written as ``item, item`` rather than ``item,item``.
3190
 
    
3191
 
    4.0.1
3192
 
    
3193
 
    2005/10/09
3194
 
    ----------
3195
 
    
3196
 
    Fixed typo in ``write`` method. (Testing for the wrong value when resetting
3197
 
    ``interpolation``).
3198
 
 
3199
 
    4.0.0 Final
3200
 
    
3201
 
    2005/09/16
3202
 
    ----------
3203
 
    
3204
 
    Fixed bug in ``setdefault`` - creating a new section *wouldn't* return
3205
 
    a reference to the new section.
3206
 
    
3207
 
    2005/09/09
3208
 
    ----------
3209
 
    
3210
 
    Removed ``PositionError``.
3211
 
    
3212
 
    Allowed quotes around keys as documented.
3213
 
    
3214
 
    Fixed bug with commas in comments. (matched as a list value)
3215
 
    
3216
 
    Beta 5
3217
 
    
3218
 
    2005/09/07
3219
 
    ----------
3220
 
    
3221
 
    Fixed bug in initialising ConfigObj from a ConfigObj.
3222
 
    
3223
 
    Changed the mailing list address.
3224
 
    
3225
 
    Beta 4
3226
 
    
3227
 
    2005/09/03
3228
 
    ----------
3229
 
    
3230
 
    Fixed bug in ``Section.__delitem__`` oops.
3231
 
    
3232
 
    2005/08/28
3233
 
    ----------
3234
 
    
3235
 
    Interpolation is switched off before writing out files.
3236
 
    
3237
 
    Fixed bug in handling ``StringIO`` instances. (Thanks to report from
3238
 
    "Gustavo Niemeyer" <gustavo@niemeyer.net>)
3239
 
    
3240
 
    Moved the doctests from the ``__init__`` method to a separate function.
3241
 
    (For the sake of IDE calltips).
3242
 
    
3243
 
    Beta 3
3244
 
    
3245
 
    2005/08/26
3246
 
    ----------
3247
 
    
3248
 
    String values unchanged by validation *aren't* reset. This preserves
3249
 
    interpolation in string values.
3250
 
    
3251
 
    2005/08/18
3252
 
    ----------
3253
 
    
3254
 
    None from a default is turned to '' if stringify is off - because setting 
3255
 
    a value to None raises an error.
3256
 
    
3257
 
    Version 4.0.0-beta2
3258
 
    
3259
 
    2005/08/16
3260
 
    ----------
3261
 
    
3262
 
    By Nicola Larosa
3263
 
    
3264
 
    Actually added the RepeatSectionError class ;-)
3265
 
    
3266
 
    2005/08/15
3267
 
    ----------
3268
 
    
3269
 
    If ``stringify`` is off - list values are preserved by the ``validate``
3270
 
    method. (Bugfix)
3271
 
    
3272
 
    2005/08/14
3273
 
    ----------
3274
 
    
3275
 
    By Michael Foord
3276
 
    
3277
 
    Fixed ``simpleVal``.
3278
 
    
3279
 
    Added ``RepeatSectionError`` error if you have additional sections in a
3280
 
    section with a ``__many__`` (repeated) section.
3281
 
    
3282
 
    By Nicola Larosa
3283
 
    
3284
 
    Reworked the ConfigObj._parse, _handle_error and _multiline methods:
3285
 
    mutated the self._infile, self._index and self._maxline attributes into
3286
 
    local variables and method parameters
3287
 
    
3288
 
    Reshaped the ConfigObj._multiline method to better reflect its semantics
3289
 
    
3290
 
    Changed the "default_test" test in ConfigObj.validate to check the fix for
3291
 
    the bug in validate.Validator.check
3292
 
    
3293
 
    2005/08/13
3294
 
    ----------
3295
 
    
3296
 
    By Nicola Larosa
3297
 
    
3298
 
    Updated comments at top
3299
 
    
3300
 
    2005/08/11
3301
 
    ----------
3302
 
    
3303
 
    By Michael Foord
3304
 
    
3305
 
    Implemented repeated sections.
3306
 
    
3307
 
    By Nicola Larosa
3308
 
    
3309
 
    Added test for interpreter version: raises RuntimeError if earlier than
3310
 
    2.2
3311
 
    
3312
 
    2005/08/10
3313
 
    ----------
3314
 
   
3315
 
    By Michael Foord
3316
 
     
3317
 
    Implemented default values in configspecs.
3318
 
    
3319
 
    By Nicola Larosa
3320
 
    
3321
 
    Fixed naked except: clause in validate that was silencing the fact
3322
 
    that Python2.2 does not have dict.pop
3323
 
    
3324
 
    2005/08/08
3325
 
    ----------
3326
 
    
3327
 
    By Michael Foord
3328
 
    
3329
 
    Bug fix causing error if file didn't exist.
3330
 
    
3331
 
    2005/08/07
3332
 
    ----------
3333
 
    
3334
 
    By Nicola Larosa
3335
 
    
3336
 
    Adjusted doctests for Python 2.2.3 compatibility
3337
 
    
3338
 
    2005/08/04
3339
 
    ----------
3340
 
    
3341
 
    By Michael Foord
3342
 
    
3343
 
    Added the inline_comments attribute
3344
 
    
3345
 
    We now preserve and rewrite all comments in the config file
3346
 
    
3347
 
    configspec is now a section attribute
3348
 
    
3349
 
    The validate method changes values in place
3350
 
    
3351
 
    Added InterpolationError
3352
 
    
3353
 
    The errors now have line number, line, and message attributes. This
3354
 
    simplifies error handling
3355
 
    
3356
 
    Added __docformat__
3357
 
    
3358
 
    2005/08/03
3359
 
    ----------
3360
 
    
3361
 
    By Michael Foord
3362
 
    
3363
 
    Fixed bug in Section.pop (now doesn't raise KeyError if a default value
3364
 
    is specified)
3365
 
    
3366
 
    Replaced ``basestring`` with ``types.StringTypes``
3367
 
    
3368
 
    Removed the ``writein`` method
3369
 
    
3370
 
    Added __version__
3371
 
    
3372
 
    2005/07/29
3373
 
    ----------
3374
 
    
3375
 
    By Nicola Larosa
3376
 
    
3377
 
    Indentation in config file is not significant anymore, subsections are
3378
 
    designated by repeating square brackets
3379
 
    
3380
 
    Adapted all tests and docs to the new format
3381
 
    
3382
 
    2005/07/28
3383
 
    ----------
3384
 
    
3385
 
    By Nicola Larosa
3386
 
    
3387
 
    Added more tests
3388
 
    
3389
 
    2005/07/23
3390
 
    ----------
3391
 
    
3392
 
    By Nicola Larosa
3393
 
    
3394
 
    Reformatted final docstring in ReST format, indented it for easier folding
3395
 
    
3396
 
    Code tests converted to doctest format, and scattered them around
3397
 
    in various docstrings
3398
 
    
3399
 
    Walk method rewritten using scalars and sections attributes
3400
 
    
3401
 
    2005/07/22
3402
 
    ----------
3403
 
    
3404
 
    By Nicola Larosa
3405
 
    
3406
 
    Changed Validator and SimpleVal "test" methods to "check"
3407
 
    
3408
 
    More code cleanup
3409
 
    
3410
 
    2005/07/21
3411
 
    ----------
3412
 
    
3413
 
    Changed Section.sequence to Section.scalars and Section.sections
3414
 
    
3415
 
    Added Section.configspec
3416
 
    
3417
 
    Sections in the root section now have no extra indentation
3418
 
    
3419
 
    Comments now better supported in Section and preserved by ConfigObj
3420
 
    
3421
 
    Comments also written out
3422
 
    
3423
 
    Implemented initial_comment and final_comment
3424
 
    
3425
 
    A scalar value after a section will now raise an error
3426
 
    
3427
 
    2005/07/20
3428
 
    ----------
3429
 
    
3430
 
    Fixed a couple of bugs
3431
 
    
3432
 
    Can now pass a tuple instead of a list
3433
 
    
3434
 
    Simplified dict and walk methods
3435
 
    
3436
 
    Added __str__ to Section
3437
 
    
3438
 
    2005/07/10
3439
 
    ----------
3440
 
    
3441
 
    By Nicola Larosa
3442
 
    
3443
 
    More code cleanup
3444
 
    
3445
 
    2005/07/08
3446
 
    ----------
3447
 
    
3448
 
    The stringify option implemented. On by default.
3449
 
    
3450
 
    2005/07/07
3451
 
    ----------
3452
 
    
3453
 
    Renamed private attributes with a single underscore prefix.
3454
 
    
3455
 
    Changes to interpolation - exceeding recursion depth, or specifying a
3456
 
    missing value, now raise errors.
3457
 
    
3458
 
    Changes for Python 2.2 compatibility. (changed boolean tests - removed
3459
 
    ``is True`` and ``is False``)
3460
 
    
3461
 
    Added test for duplicate section and member (and fixed bug)
3462
 
    
3463
 
    2005/07/06
3464
 
    ----------
3465
 
    
3466
 
    By Nicola Larosa
3467
 
    
3468
 
    Code cleanup
3469
 
    
3470
 
    2005/07/02
3471
 
    ----------
3472
 
    
3473
 
    Version 0.1.0
3474
 
    
3475
 
    Now properly handles values including comments and lists.
3476
 
    
3477
 
    Better error handling.
3478
 
    
3479
 
    String interpolation.
3480
 
    
3481
 
    Some options implemented.
3482
 
    
3483
 
    You can pass a Section a dictionary to initialise it.
3484
 
    
3485
 
    Setting a Section member to a dictionary will create a Section instance.
3486
 
    
3487
 
    2005/06/26
3488
 
    ----------
3489
 
    
3490
 
    Version 0.0.1
3491
 
    
3492
 
    Experimental reader.
3493
 
    
3494
 
    A reasonably elegant implementation - a basic reader in 160 lines of code.
3495
 
    
3496
 
    *A programming language is a medium of expression.* - Paul Graham
3497
 
"""
3498
 
 
 
2461
"""*A programming language is a medium of expression.* - Paul Graham"""