blob: a48d54bb91d4a4675974fb025baa73135baa6265 [file] [log] [blame]
Guido van Rossum3d209861997-12-09 16:10:31 +00001"""Configuration file parser.
2
3A setup file consists of sections, lead by a "[section]" header,
4and followed by "name: value" entries, with continuations and such in
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00005the style of RFC 822.
Guido van Rossum3d209861997-12-09 16:10:31 +00006
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00007The option values can contain format strings which refer to other values in
8the same section, or values in a special [DEFAULT] section.
9
Guido van Rossum3d209861997-12-09 16:10:31 +000010For example:
11
12 something: %(dir)s/whatever
13
14would resolve the "%(dir)s" to the value of dir. All reference
15expansions are done late, on demand.
16
17Intrinsic defaults can be specified by passing them into the
18ConfigParser constructor as a dictionary.
19
20class:
21
22ConfigParser -- responsible for for parsing a list of
23 configuration files, and managing the parsed database.
24
25 methods:
26
Barry Warsawf09f6a51999-01-26 22:01:37 +000027 __init__(defaults=None)
28 create the parser and specify a dictionary of intrinsic defaults. The
29 keys must be strings, the values must be appropriate for %()s string
30 interpolation. Note that `__name__' is always an intrinsic default;
31 it's value is the section's name.
Guido van Rossum3d209861997-12-09 16:10:31 +000032
Barry Warsawf09f6a51999-01-26 22:01:37 +000033 sections()
34 return all the configuration section names, sans DEFAULT
Guido van Rossum3d209861997-12-09 16:10:31 +000035
Guido van Rossuma5a24b71999-10-04 19:58:22 +000036 has_section(section)
37 return whether the given section exists
38
Eric S. Raymond649685a2000-07-14 14:28:22 +000039 has_option(section, option)
40 return whether the given option exists in the given section
41
Barry Warsawf09f6a51999-01-26 22:01:37 +000042 options(section)
43 return list of configuration options for the named section
Guido van Rossum3d209861997-12-09 16:10:31 +000044
Guido van Rossumc0780ac1999-01-30 04:35:47 +000045 read(filenames)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000046 read and parse the list of named configuration files, given by
47 name. A single filename is also allowed. Non-existing files
48 are ignored.
49
50 readfp(fp, filename=None)
51 read and parse one configuration file, given as a file object.
52 The filename defaults to fp.name; it is only used in error
Barry Warsaw25394511999-10-12 16:12:48 +000053 messages (if fp has no `name' attribute, the string `<???>' is used).
Guido van Rossum3d209861997-12-09 16:10:31 +000054
Neal Norwitzf680cc42002-12-17 01:56:47 +000055 get(section, option, raw=False, vars=None)
Barry Warsawf09f6a51999-01-26 22:01:37 +000056 return a string value for the named option. All % interpolations are
57 expanded in the return values, based on the defaults passed into the
58 constructor and the DEFAULT section. Additional substitutions may be
59 provided using the `vars' argument, which must be a dictionary whose
60 contents override any pre-existing defaults.
Guido van Rossum3d209861997-12-09 16:10:31 +000061
Barry Warsawf09f6a51999-01-26 22:01:37 +000062 getint(section, options)
63 like get(), but convert value to an integer
Guido van Rossum3d209861997-12-09 16:10:31 +000064
Barry Warsawf09f6a51999-01-26 22:01:37 +000065 getfloat(section, options)
66 like get(), but convert value to a float
Guido van Rossum3d209861997-12-09 16:10:31 +000067
Barry Warsawf09f6a51999-01-26 22:01:37 +000068 getboolean(section, options)
Guido van Rossumfb06f752001-10-04 19:58:46 +000069 like get(), but convert value to a boolean (currently case
Neal Norwitzf680cc42002-12-17 01:56:47 +000070 insensitively defined as 0, false, no, off for False, and 1, true,
71 yes, on for True). Returns False or True.
Eric S. Raymond649685a2000-07-14 14:28:22 +000072
Neal Norwitzf680cc42002-12-17 01:56:47 +000073 items(section, raw=False, vars=None)
Fred Drake2ca041f2002-09-27 15:49:56 +000074 return a list of tuples with (name, value) for each option
75 in the section.
76
Eric S. Raymond649685a2000-07-14 14:28:22 +000077 remove_section(section)
Tim Peters88869f92001-01-14 23:36:06 +000078 remove the given file section and all its options
Eric S. Raymond649685a2000-07-14 14:28:22 +000079
80 remove_option(section, option)
Tim Peters88869f92001-01-14 23:36:06 +000081 remove the given option from the given section
Eric S. Raymond649685a2000-07-14 14:28:22 +000082
83 set(section, option, value)
84 set the given option
85
86 write(fp)
Tim Peters88869f92001-01-14 23:36:06 +000087 write the configuration state in .ini format
Guido van Rossum3d209861997-12-09 16:10:31 +000088"""
89
Barry Warsawbfa3f6b1998-07-01 20:41:12 +000090import re
Guido van Rossum3d209861997-12-09 16:10:31 +000091
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000092__all__ = ["NoSectionError","DuplicateSectionError","NoOptionError",
93 "InterpolationError","InterpolationDepthError","ParsingError",
94 "MissingSectionHeaderError","ConfigParser",
Fred Drakec2ff9052002-09-27 15:33:11 +000095 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000096
Guido van Rossum3d209861997-12-09 16:10:31 +000097DEFAULTSECT = "DEFAULT"
98
Fred Drake2a37f9f2000-09-27 22:43:54 +000099MAX_INTERPOLATION_DEPTH = 10
100
Guido van Rossum3d209861997-12-09 16:10:31 +0000101
Tim Peters88869f92001-01-14 23:36:06 +0000102
Guido van Rossum3d209861997-12-09 16:10:31 +0000103# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000104class Error(Exception):
Guido van Rossum3d209861997-12-09 16:10:31 +0000105 def __init__(self, msg=''):
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000106 self._msg = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000107 Exception.__init__(self, msg)
Guido van Rossum3d209861997-12-09 16:10:31 +0000108 def __repr__(self):
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000109 return self._msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000110 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000111
112class NoSectionError(Error):
113 def __init__(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000114 Error.__init__(self, 'No section: %s' % section)
115 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000116
117class DuplicateSectionError(Error):
118 def __init__(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000119 Error.__init__(self, "Section %s already exists" % section)
120 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000121
122class NoOptionError(Error):
123 def __init__(self, option, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000124 Error.__init__(self, "No option `%s' in section: %s" %
125 (option, section))
126 self.option = option
127 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000128
129class InterpolationError(Error):
Barry Warsaw64462121998-08-06 18:48:41 +0000130 def __init__(self, reference, option, section, rawval):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000131 Error.__init__(self,
Barry Warsaw64462121998-08-06 18:48:41 +0000132 "Bad value substitution:\n"
133 "\tsection: [%s]\n"
134 "\toption : %s\n"
135 "\tkey : %s\n"
136 "\trawval : %s\n"
137 % (section, option, reference, rawval))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000138 self.reference = reference
139 self.option = option
140 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000141
Neal Norwitzce1d9442002-12-30 23:38:47 +0000142class InterpolationSyntaxError(Error): pass
143
Fred Drake2a37f9f2000-09-27 22:43:54 +0000144class InterpolationDepthError(Error):
145 def __init__(self, option, section, rawval):
146 Error.__init__(self,
147 "Value interpolation too deeply recursive:\n"
148 "\tsection: [%s]\n"
149 "\toption : %s\n"
150 "\trawval : %s\n"
151 % (section, option, rawval))
152 self.option = option
153 self.section = section
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000154
155class ParsingError(Error):
156 def __init__(self, filename):
157 Error.__init__(self, 'File contains parsing errors: %s' % filename)
158 self.filename = filename
159 self.errors = []
160
161 def append(self, lineno, line):
162 self.errors.append((lineno, line))
163 self._msg = self._msg + '\n\t[line %2d]: %s' % (lineno, line)
164
Fred Drake2a37f9f2000-09-27 22:43:54 +0000165class MissingSectionHeaderError(ParsingError):
166 def __init__(self, filename, lineno, line):
167 Error.__init__(
168 self,
169 'File contains no section headers.\nfile: %s, line: %d\n%s' %
170 (filename, lineno, line))
171 self.filename = filename
172 self.lineno = lineno
173 self.line = line
174
Guido van Rossum3d209861997-12-09 16:10:31 +0000175
Tim Peters88869f92001-01-14 23:36:06 +0000176
Fred Drakefce65572002-10-25 18:08:18 +0000177class RawConfigParser:
Guido van Rossum3d209861997-12-09 16:10:31 +0000178 def __init__(self, defaults=None):
Fred Drakefce65572002-10-25 18:08:18 +0000179 self._sections = {}
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000180 if defaults is None:
Fred Drakefce65572002-10-25 18:08:18 +0000181 self._defaults = {}
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000182 else:
Fred Drakefce65572002-10-25 18:08:18 +0000183 self._defaults = defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000184
185 def defaults(self):
Fred Drakefce65572002-10-25 18:08:18 +0000186 return self._defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000187
188 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000189 """Return a list of section names, excluding [DEFAULT]"""
Fred Drakefce65572002-10-25 18:08:18 +0000190 # self._sections will never have [DEFAULT] in it
191 return self._sections.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000192
193 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000194 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000195
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000196 Raise DuplicateSectionError if a section by the specified name
197 already exists.
198 """
Fred Drakefce65572002-10-25 18:08:18 +0000199 if section in self._sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000200 raise DuplicateSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000201 self._sections[section] = {}
Guido van Rossum3d209861997-12-09 16:10:31 +0000202
203 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000204 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000205
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000206 The DEFAULT section is not acknowledged.
207 """
Fred Drakefce65572002-10-25 18:08:18 +0000208 return section in self._sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000209
210 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000211 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000212 try:
Fred Drakefce65572002-10-25 18:08:18 +0000213 opts = self._sections[section].copy()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000214 except KeyError:
215 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000216 opts.update(self._defaults)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000217 if '__name__' in opts:
Fred Drake2a37f9f2000-09-27 22:43:54 +0000218 del opts['__name__']
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000219 return opts.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000220
221 def read(self, filenames):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000222 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000223
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000224 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000225 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000226 configuration file locations (e.g. current directory, user's
227 home directory, systemwide directory), and all existing
228 configuration files in the list will be read. A single
229 filename may also be given.
230 """
Walter Dörwald65230a22002-06-03 15:58:32 +0000231 if isinstance(filenames, basestring):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000232 filenames = [filenames]
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000233 for filename in filenames:
234 try:
235 fp = open(filename)
236 except IOError:
237 continue
Fred Drakefce65572002-10-25 18:08:18 +0000238 self._read(fp, filename)
Fred Drake2438a481999-10-04 18:11:56 +0000239 fp.close()
Guido van Rossum3d209861997-12-09 16:10:31 +0000240
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000241 def readfp(self, fp, filename=None):
242 """Like read() but the argument must be a file-like object.
243
244 The `fp' argument must have a `readline' method. Optional
245 second argument is the `filename', which if not given, is
246 taken from fp.name. If fp has no `name' attribute, `<???>' is
247 used.
248
249 """
250 if filename is None:
251 try:
252 filename = fp.name
253 except AttributeError:
254 filename = '<???>'
Fred Drakefce65572002-10-25 18:08:18 +0000255 self._read(fp, filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000256
Fred Drakefce65572002-10-25 18:08:18 +0000257 def get(self, section, option):
258 opt = self.optionxform(option)
259 if section not in self._sections:
Fred Drakec2ff9052002-09-27 15:33:11 +0000260 if section != DEFAULTSECT:
261 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000262 if opt in self._defaults:
263 return self._defaults[opt]
264 else:
265 raise NoOptionError(option, section)
266 elif opt in self._sections[section]:
267 return self._sections[section][opt]
268 elif opt in self._defaults:
269 return self._defaults[opt]
270 else:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000271 raise NoOptionError(option, section)
Fred Drake2a37f9f2000-09-27 22:43:54 +0000272
Fred Drakefce65572002-10-25 18:08:18 +0000273 def items(self, section):
Fred Drake2ca041f2002-09-27 15:49:56 +0000274 try:
Fred Drakefce65572002-10-25 18:08:18 +0000275 d2 = self._sections[section]
Fred Drake2ca041f2002-09-27 15:49:56 +0000276 except KeyError:
277 if section != DEFAULTSECT:
278 raise NoSectionError(section)
Fred Drakedf393bd2002-10-25 20:41:30 +0000279 d2 = {}
Fred Drakefce65572002-10-25 18:08:18 +0000280 d = self._defaults.copy()
281 d.update(d2)
Fred Drakedf393bd2002-10-25 20:41:30 +0000282 if "__name__" in d:
283 del d["__name__"]
Fred Drakefce65572002-10-25 18:08:18 +0000284 return d.items()
Fred Drake2ca041f2002-09-27 15:49:56 +0000285
Fred Drakefce65572002-10-25 18:08:18 +0000286 def _get(self, section, conv, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000287 return conv(self.get(section, option))
Guido van Rossum3d209861997-12-09 16:10:31 +0000288
289 def getint(self, section, option):
Fred Drakefce65572002-10-25 18:08:18 +0000290 return self._get(section, int, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000291
292 def getfloat(self, section, option):
Fred Drakefce65572002-10-25 18:08:18 +0000293 return self._get(section, float, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000294
Fred Drakec2ff9052002-09-27 15:33:11 +0000295 _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
296 '0': False, 'no': False, 'false': False, 'off': False}
297
Guido van Rossum3d209861997-12-09 16:10:31 +0000298 def getboolean(self, section, option):
Tim Peterse0c446b2001-10-18 21:57:37 +0000299 v = self.get(section, option)
Fred Drakec2ff9052002-09-27 15:33:11 +0000300 if v.lower() not in self._boolean_states:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000301 raise ValueError, 'Not a boolean: %s' % v
Fred Drakec2ff9052002-09-27 15:33:11 +0000302 return self._boolean_states[v.lower()]
Guido van Rossum3d209861997-12-09 16:10:31 +0000303
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000304 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000305 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000306
Eric S. Raymond417c4892000-07-10 18:11:00 +0000307 def has_option(self, section, option):
308 """Check for the existence of a given option in a given section."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000309 if not section or section == DEFAULTSECT:
310 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000311 return option in self._defaults
312 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000313 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000314 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000315 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000316 return (option in self._sections[section]
317 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000318
319 def set(self, section, option, value):
320 """Set an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000321 if not section or section == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000322 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000323 else:
324 try:
Fred Drakefce65572002-10-25 18:08:18 +0000325 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000326 except KeyError:
327 raise NoSectionError(section)
Fred Drakec2ff9052002-09-27 15:33:11 +0000328 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000329
330 def write(self, fp):
331 """Write an .ini-format representation of the configuration state."""
Fred Drakefce65572002-10-25 18:08:18 +0000332 if self._defaults:
Fred Drakec2ff9052002-09-27 15:33:11 +0000333 fp.write("[%s]\n" % DEFAULTSECT)
Fred Drakefce65572002-10-25 18:08:18 +0000334 for (key, value) in self._defaults.items():
Andrew M. Kuchling00824ed2002-03-08 18:08:47 +0000335 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000336 fp.write("\n")
Fred Drakefce65572002-10-25 18:08:18 +0000337 for section in self._sections:
Fred Drakec2ff9052002-09-27 15:33:11 +0000338 fp.write("[%s]\n" % section)
Fred Drakefce65572002-10-25 18:08:18 +0000339 for (key, value) in self._sections[section].items():
Fred Drakec2ff9052002-09-27 15:33:11 +0000340 if key != "__name__":
341 fp.write("%s = %s\n" %
342 (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000343 fp.write("\n")
344
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000345 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000346 """Remove an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000347 if not section or section == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000348 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000349 else:
350 try:
Fred Drakefce65572002-10-25 18:08:18 +0000351 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000352 except KeyError:
353 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000354 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000355 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000356 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000357 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000358 return existed
359
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000360 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000361 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000362 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000363 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000364 del self._sections[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000365 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000366
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000367 #
Fred Drakec2ff9052002-09-27 15:33:11 +0000368 # Regular expressions for parsing section headers and options.
369 #
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000370 SECTCRE = re.compile(
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000371 r'\[' # [
Fred Draked4df94b2001-02-14 15:24:17 +0000372 r'(?P<header>[^]]+)' # very permissive!
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000373 r'\]' # ]
374 )
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000375 OPTCRE = re.compile(
Fred Drake176916a2002-09-27 16:21:18 +0000376 r'(?P<option>[^:=\s][^:=]*)' # very permissive!
Fred Drakec2ff9052002-09-27 15:33:11 +0000377 r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000378 # followed by separator
379 # (either : or =), followed
380 # by any # space/tab
381 r'(?P<value>.*)$' # everything up to eol
382 )
383
Fred Drakefce65572002-10-25 18:08:18 +0000384 def _read(self, fp, fpname):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000385 """Parse a sectioned setup file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000386
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000387 The sections in setup file contains a title line at the top,
388 indicated by a name in square brackets (`[]'), plus key/value
389 options lines, indicated by `name: value' format lines.
Andrew M. Kuchling9050a512002-11-06 14:51:20 +0000390 Continuations are represented by an embedded newline then
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000391 leading whitespace. Blank lines, lines beginning with a '#',
Andrew M. Kuchling9050a512002-11-06 14:51:20 +0000392 and just about everything else are ignored.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000393 """
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000394 cursect = None # None, or a dictionary
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000395 optname = None
396 lineno = 0
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000397 e = None # None, or an exception
Neal Norwitzf680cc42002-12-17 01:56:47 +0000398 while True:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000399 line = fp.readline()
400 if not line:
401 break
402 lineno = lineno + 1
403 # comment or blank line?
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000404 if line.strip() == '' or line[0] in '#;':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000405 continue
Fred Drake176916a2002-09-27 16:21:18 +0000406 if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
407 # no leading whitespace
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000408 continue
409 # continuation line?
Fred Drakec2ff9052002-09-27 15:33:11 +0000410 if line[0].isspace() and cursect is not None and optname:
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000411 value = line.strip()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000412 if value:
Fred Drakec2ff9052002-09-27 15:33:11 +0000413 cursect[optname] = "%s\n%s" % (cursect[optname], value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000414 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000415 else:
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000416 # is it a section header?
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000417 mo = self.SECTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000418 if mo:
419 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +0000420 if sectname in self._sections:
421 cursect = self._sections[sectname]
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000422 elif sectname == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000423 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000424 else:
Barry Warsaw64462121998-08-06 18:48:41 +0000425 cursect = {'__name__': sectname}
Fred Drakefce65572002-10-25 18:08:18 +0000426 self._sections[sectname] = cursect
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000427 # So sections can't start with a continuation line
428 optname = None
429 # no section header in the file?
430 elif cursect is None:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000431 raise MissingSectionHeaderError(fpname, lineno, `line`)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000432 # an option line?
433 else:
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000434 mo = self.OPTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000435 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +0000436 optname, vi, optval = mo.group('option', 'vi', 'value')
Jeremy Hylton820314e2000-03-03 20:43:57 +0000437 if vi in ('=', ':') and ';' in optval:
Fred Drakec517b9b2000-02-28 20:59:03 +0000438 # ';' is a comment delimiter only if it follows
439 # a spacing character
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000440 pos = optval.find(';')
Fred Drakec2ff9052002-09-27 15:33:11 +0000441 if pos != -1 and optval[pos-1].isspace():
Fred Drakec517b9b2000-02-28 20:59:03 +0000442 optval = optval[:pos]
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000443 optval = optval.strip()
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000444 # allow empty values
445 if optval == '""':
446 optval = ''
Fred Drake176916a2002-09-27 16:21:18 +0000447 optname = self.optionxform(optname.rstrip())
Fred Drakec2ff9052002-09-27 15:33:11 +0000448 cursect[optname] = optval
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000449 else:
450 # a non-fatal parsing error occurred. set up the
451 # exception but keep going. the exception will be
452 # raised at the end of the file and will contain a
453 # list of all bogus lines
454 if not e:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000455 e = ParsingError(fpname)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000456 e.append(lineno, `line`)
457 # if any parsing errors occurred, raise an exception
458 if e:
459 raise e
Fred Drakefce65572002-10-25 18:08:18 +0000460
461
462class ConfigParser(RawConfigParser):
463
Neal Norwitzf680cc42002-12-17 01:56:47 +0000464 def get(self, section, option, raw=False, vars=None):
Fred Drakefce65572002-10-25 18:08:18 +0000465 """Get an option value for a given section.
466
467 All % interpolations are expanded in the return values, based on the
468 defaults passed into the constructor, unless the optional argument
469 `raw' is true. Additional substitutions may be provided using the
470 `vars' argument, which must be a dictionary whose contents overrides
471 any pre-existing defaults.
472
473 The section DEFAULT is special.
474 """
475 d = self._defaults.copy()
476 try:
477 d.update(self._sections[section])
478 except KeyError:
479 if section != DEFAULTSECT:
480 raise NoSectionError(section)
481 # Update with the entry specific variables
482 if vars is not None:
483 d.update(vars)
484 option = self.optionxform(option)
485 try:
486 value = d[option]
487 except KeyError:
488 raise NoOptionError(option, section)
489
490 if raw:
491 return value
492 else:
493 return self._interpolate(section, option, value, d)
494
Neal Norwitzf680cc42002-12-17 01:56:47 +0000495 def items(self, section, raw=False, vars=None):
Fred Drakefce65572002-10-25 18:08:18 +0000496 """Return a list of tuples with (name, value) for each option
497 in the section.
498
499 All % interpolations are expanded in the return values, based on the
500 defaults passed into the constructor, unless the optional argument
501 `raw' is true. Additional substitutions may be provided using the
502 `vars' argument, which must be a dictionary whose contents overrides
503 any pre-existing defaults.
504
505 The section DEFAULT is special.
506 """
507 d = self._defaults.copy()
508 try:
509 d.update(self._sections[section])
510 except KeyError:
511 if section != DEFAULTSECT:
512 raise NoSectionError(section)
513 # Update with the entry specific variables
514 if vars:
515 d.update(vars)
Fred Drakedf393bd2002-10-25 20:41:30 +0000516 options = d.keys()
517 if "__name__" in options:
518 options.remove("__name__")
Fred Drakefce65572002-10-25 18:08:18 +0000519 if raw:
Fred Drakedf393bd2002-10-25 20:41:30 +0000520 for option in options:
Fred Drakefce65572002-10-25 18:08:18 +0000521 yield (option, d[option])
522 else:
Fred Drakedf393bd2002-10-25 20:41:30 +0000523 for option in options:
Fred Drakefce65572002-10-25 18:08:18 +0000524 yield (option,
525 self._interpolate(section, option, d[option], d))
526
527 def _interpolate(self, section, option, rawval, vars):
528 # do the string interpolation
529 value = rawval
Tim Peters230a60c2002-11-09 05:08:07 +0000530 depth = MAX_INTERPOLATION_DEPTH
Fred Drakefce65572002-10-25 18:08:18 +0000531 while depth: # Loop through this until it's done
532 depth -= 1
533 if value.find("%(") != -1:
534 try:
535 value = value % vars
536 except KeyError, key:
537 raise InterpolationError(key, option, section, rawval)
538 else:
539 break
540 if value.find("%(") != -1:
541 raise InterpolationDepthError(option, section, rawval)
542 return value
Fred Drake0eebd5c2002-10-25 21:52:00 +0000543
544
545class SafeConfigParser(ConfigParser):
546
547 def _interpolate(self, section, option, rawval, vars):
548 # do the string interpolation
549 L = []
550 self._interpolate_some(option, L, rawval, section, vars, 1)
551 return ''.join(L)
552
553 _interpvar_match = re.compile(r"%\(([^)]+)\)s").match
554
555 def _interpolate_some(self, option, accum, rest, section, map, depth):
556 if depth > MAX_INTERPOLATION_DEPTH:
557 raise InterpolationDepthError(option, section, rest)
558 while rest:
559 p = rest.find("%")
560 if p < 0:
561 accum.append(rest)
562 return
563 if p > 0:
564 accum.append(rest[:p])
565 rest = rest[p:]
566 # p is no longer used
567 c = rest[1:2]
568 if c == "%":
569 accum.append("%")
570 rest = rest[2:]
571 elif c == "(":
572 m = self._interpvar_match(rest)
573 if m is None:
574 raise InterpolationSyntaxError(
575 "bad interpolation variable syntax at: %r" % rest)
576 var = m.group(1)
577 rest = rest[m.end():]
578 try:
579 v = map[var]
580 except KeyError:
581 raise InterpolationError(
582 "no value found for %r" % var)
583 if "%" in v:
584 self._interpolate_some(option, accum, v,
585 section, map, depth + 1)
586 else:
587 accum.append(v)
588 else:
589 raise InterpolationSyntaxError(
590 "'%' must be followed by '%' or '('")