summaryrefslogtreecommitdiff
path: root/iniparse/compat.py
blob: db89ed888c31ee323209c0d074942cdfcf91c212 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# Copyright (c) 2001, 2002, 2003 Python Software Foundation
# Copyright (c) 2004-2008 Paramjit Oberoi <param.cs.wisc.edu>
# All Rights Reserved.  See LICENSE-PSF & LICENSE for details.

"""Compatibility interfaces for ConfigParser

Interfaces of ConfigParser, RawConfigParser and SafeConfigParser
should be completely identical to the Python standard library
versions.  Tested with the unit tests included with Python-2.3.4

The underlying INIConfig object can be accessed as cfg.data
"""

import re
from ConfigParser import DuplicateSectionError,    \
                  NoSectionError, NoOptionError,   \
                  InterpolationMissingOptionError, \
                  InterpolationDepthError,         \
                  InterpolationSyntaxError,        \
                  DEFAULTSECT, MAX_INTERPOLATION_DEPTH

# These are imported only for compatiability.
# The code below does not reference them directly.
from ConfigParser import Error, InterpolationError, \
                  MissingSectionHeaderError, ParsingError

import ini

class RawConfigParser(object):
    def __init__(self, defaults=None, dict_type=dict):
        if dict_type != dict:
            raise ValueError('Custom dict types not supported')
        self.data = ini.INIConfig(defaults=defaults, optionxformsource=self)

    def optionxform(self, optionstr):
        return optionstr.lower()

    def defaults(self):
        d = {}
        secobj = self.data._defaults
        for name in secobj._options:
            d[name] = secobj._compat_get(name)
        return d

    def sections(self):
        """Return a list of section names, excluding [DEFAULT]"""
        return list(self.data)

    def add_section(self, section):
        """Create a new section in the configuration.

        Raise DuplicateSectionError if a section by the specified name
        already exists.  Raise ValueError if name is DEFAULT or any of
        its case-insensitive variants.
        """
        # The default section is the only one that gets the case-insensitive
        # treatment - so it is special-cased here.
        if section.lower() == "default":
            raise ValueError, 'Invalid section name: %s' % section

        if self.has_section(section):
            raise DuplicateSectionError(section)
        else:
            self.data._new_namespace(section)

    def has_section(self, section):
        """Indicate whether the named section is present in the configuration.

        The DEFAULT section is not acknowledged.
        """
        return (section in self.data)

    def options(self, section):
        """Return a list of option names for the given section name."""
        if section in self.data:
            return list(self.data[section])
        else:
            raise NoSectionError(section)

    def read(self, filenames):
        """Read and parse a filename or a list of filenames.

        Files that cannot be opened are silently ignored; this is
        designed so that you can specify a list of potential
        configuration file locations (e.g. current directory, user's
        home directory, systemwide directory), and all existing
        configuration files in the list will be read.  A single
        filename may also be given.
        """
        files_read = []
        if isinstance(filenames, basestring):
            filenames = [filenames]
        for filename in filenames:
            try:
                fp = open(filename)
            except IOError:
                continue
            files_read.append(filename)
            self.data._readfp(fp)
            fp.close()
        return files_read

    def readfp(self, fp, filename=None):
        """Like read() but the argument must be a file-like object.

        The `fp' argument must have a `readline' method.  Optional
        second argument is the `filename', which if not given, is
        taken from fp.name.  If fp has no `name' attribute, `<???>' is
        used.
        """
        self.data._readfp(fp)

    def get(self, section, option, vars=None):
        if not self.has_section(section):
            raise NoSectionError(section)
        if vars is not None and option in vars:
            value = vars[option]

        sec = self.data[section]
        if option in sec:
            return sec._compat_get(option)
        else:
            raise NoOptionError(option, section)

    def items(self, section):
        if section in self.data:
            ans = []
            for opt in self.data[section]:
                ans.append((opt, self.get(section, opt)))
            return ans
        else:
            raise NoSectionError(section)

    def getint(self, section, option):
        return int(self.get(section, option))

    def getfloat(self, section, option):
        return float(self.get(section, option))

    _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
                       '0': False, 'no': False, 'false': False, 'off': False}

    def getboolean(self, section, option):
        v = self.get(section, option)
        if v.lower() not in self._boolean_states:
            raise ValueError, 'Not a boolean: %s' % v
        return self._boolean_states[v.lower()]

    def has_option(self, section, option):
        """Check for the existence of a given option in a given section."""
        if section in self.data:
            sec = self.data[section]
        else:
            raise NoSectionError(section)
        return (option in sec)

    def set(self, section, option, value):
        """Set an option."""
        if section in self.data:
            self.data[section][option] = value
        else:
            raise NoSectionError(section)

    def write(self, fp):
        """Write an .ini-format representation of the configuration state."""
        fp.write(str(self.data))

    def remove_option(self, section, option):
        """Remove an option."""
        if section in self.data:
            sec = self.data[section]
        else:
            raise NoSectionError(section)
        if option in sec:
            del sec[option]
            return 1
        else:
            return 0

    def remove_section(self, section):
        """Remove a file section."""
        if not self.has_section(section):
            return False
        del self.data[section]
        return True


class ConfigDict(object):
    """Present a dict interface to a ini section."""

    def __init__(self, cfg, section, vars):
        self.cfg = cfg
        self.section = section
        self.vars = vars

    def __getitem__(self, key):
        try:
            return RawConfigParser.get(self.cfg, self.section, key, self.vars)
        except (NoOptionError, NoSectionError):
            raise KeyError(key)


class ConfigParser(RawConfigParser):

    def get(self, section, option, raw=False, vars=None):
        """Get an option value for a given section.

        All % interpolations are expanded in the return values, based on the
        defaults passed into the constructor, unless the optional argument
        `raw' is true.  Additional substitutions may be provided using the
        `vars' argument, which must be a dictionary whose contents overrides
        any pre-existing defaults.

        The section DEFAULT is special.
        """
        if section != DEFAULTSECT and not self.has_section(section):
            raise NoSectionError(section)

        option = self.optionxform(option)
        value = RawConfigParser.get(self, section, option, vars)

        if raw:
            return value
        else:
            d = ConfigDict(self, section, vars)
            return self._interpolate(section, option, value, d)

    def _interpolate(self, section, option, rawval, vars):
        # do the string interpolation
        value = rawval
        depth = MAX_INTERPOLATION_DEPTH
        while depth:                    # Loop through this until it's done
            depth -= 1
            if "%(" in value:
                try:
                    value = value % vars
                except KeyError, e:
                    raise InterpolationMissingOptionError(
                        option, section, rawval, e.args[0])
            else:
                break
        if value.find("%(") != -1:
            raise InterpolationDepthError(option, section, rawval)
        return value

    def items(self, section, raw=False, vars=None):
        """Return a list of tuples with (name, value) for each option
        in the section.

        All % interpolations are expanded in the return values, based on the
        defaults passed into the constructor, unless the optional argument
        `raw' is true.  Additional substitutions may be provided using the
        `vars' argument, which must be a dictionary whose contents overrides
        any pre-existing defaults.

        The section DEFAULT is special.
        """
        if section != DEFAULTSECT and not self.has_section(section):
            raise NoSectionError(section)
        if vars is None:
            options = list(self.data[section])
        else:
            options = []
            for x in self.data[section]:
                if x not in vars:
                    options.append(x)
            options.extend(vars.keys())

        if "__name__" in options:
            options.remove("__name__")

        d = ConfigDict(self, section, vars)
        if raw:
            return [(option, d[option])
                    for option in options]
        else:
            return [(option, self._interpolate(section, option, d[option], d))
                    for option in options]


class SafeConfigParser(ConfigParser):
    _interpvar_re = re.compile(r"%\(([^)]+)\)s")
    _badpercent_re = re.compile(r"%[^%]|%$")

    def set(self, section, option, value):
        if not isinstance(value, basestring):
            raise TypeError("option values must be strings")
        # check for bad percent signs:
        # first, replace all "good" interpolations
        tmp_value = self._interpvar_re.sub('', value)
        # then, check if there's a lone percent sign left
        m = self._badpercent_re.search(tmp_value)
        if m:
            raise ValueError("invalid interpolation syntax in %r at "
                             "position %d" % (value, m.start()))

        ConfigParser.set(self, section, option, value)

    def _interpolate(self, section, option, rawval, vars):
        # do the string interpolation
        L = []
        self._interpolate_some(option, L, rawval, section, vars, 1)
        return ''.join(L)

    _interpvar_match = re.compile(r"%\(([^)]+)\)s").match

    def _interpolate_some(self, option, accum, rest, section, map, depth):
        if depth > MAX_INTERPOLATION_DEPTH:
            raise InterpolationDepthError(option, section, rest)
        while rest:
            p = rest.find("%")
            if p < 0:
                accum.append(rest)
                return
            if p > 0:
                accum.append(rest[:p])
                rest = rest[p:]
            # p is no longer used
            c = rest[1:2]
            if c == "%":
                accum.append("%")
                rest = rest[2:]
            elif c == "(":
                m = self._interpvar_match(rest)
                if m is None:
                    raise InterpolationSyntaxError(option, section,
                        "bad interpolation variable reference %r" % rest)
                var = m.group(1)
                rest = rest[m.end():]
                try:
                    v = map[var]
                except KeyError:
                    raise InterpolationMissingOptionError(
                        option, section, rest, var)
                if "%" in v:
                    self._interpolate_some(option, accum, v,
                                           section, map, depth + 1)
                else:
                    accum.append(v)
            else:
                raise InterpolationSyntaxError(
                    option, section,
                    "'%' must be followed by '%' or '(', found: " + repr(rest))