blob: 842a576cef678118acbd538aa20e09b2486dc982 [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
Barry Warsawf09f6a51999-01-26 22:01:37 +000055 get(section, option, raw=0, vars=None)
56 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
70 insensitively defined as 0, false, no, off for 0, and 1, true,
71 yes, on for 1). Returns 0 or 1.
Eric S. Raymond649685a2000-07-14 14:28:22 +000072
Fred Drake2ca041f2002-09-27 15:49:56 +000073 items(section, raw=0, vars=None)
74 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
Fred Drake2a37f9f2000-09-27 22:43:54 +0000142class InterpolationDepthError(Error):
143 def __init__(self, option, section, rawval):
144 Error.__init__(self,
145 "Value interpolation too deeply recursive:\n"
146 "\tsection: [%s]\n"
147 "\toption : %s\n"
148 "\trawval : %s\n"
149 % (section, option, rawval))
150 self.option = option
151 self.section = section
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000152
153class ParsingError(Error):
154 def __init__(self, filename):
155 Error.__init__(self, 'File contains parsing errors: %s' % filename)
156 self.filename = filename
157 self.errors = []
158
159 def append(self, lineno, line):
160 self.errors.append((lineno, line))
161 self._msg = self._msg + '\n\t[line %2d]: %s' % (lineno, line)
162
Fred Drake2a37f9f2000-09-27 22:43:54 +0000163class MissingSectionHeaderError(ParsingError):
164 def __init__(self, filename, lineno, line):
165 Error.__init__(
166 self,
167 'File contains no section headers.\nfile: %s, line: %d\n%s' %
168 (filename, lineno, line))
169 self.filename = filename
170 self.lineno = lineno
171 self.line = line
172
Guido van Rossum3d209861997-12-09 16:10:31 +0000173
Tim Peters88869f92001-01-14 23:36:06 +0000174
Guido van Rossum3d209861997-12-09 16:10:31 +0000175class ConfigParser:
176 def __init__(self, defaults=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000177 self.__sections = {}
178 if defaults is None:
179 self.__defaults = {}
180 else:
181 self.__defaults = defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000182
183 def defaults(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000184 return self.__defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000185
186 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000187 """Return a list of section names, excluding [DEFAULT]"""
188 # self.__sections will never have [DEFAULT] in it
189 return self.__sections.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000190
191 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000192 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000193
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000194 Raise DuplicateSectionError if a section by the specified name
195 already exists.
196 """
Raymond Hettinger54f02222002-06-01 14:18:47 +0000197 if section in self.__sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000198 raise DuplicateSectionError(section)
199 self.__sections[section] = {}
Guido van Rossum3d209861997-12-09 16:10:31 +0000200
201 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000202 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000203
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000204 The DEFAULT section is not acknowledged.
205 """
Fred Drakec2ff9052002-09-27 15:33:11 +0000206 return section in self.__sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000207
208 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000209 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000210 try:
211 opts = self.__sections[section].copy()
212 except KeyError:
213 raise NoSectionError(section)
214 opts.update(self.__defaults)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000215 if '__name__' in opts:
Fred Drake2a37f9f2000-09-27 22:43:54 +0000216 del opts['__name__']
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000217 return opts.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000218
219 def read(self, filenames):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000220 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000221
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000222 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000223 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000224 configuration file locations (e.g. current directory, user's
225 home directory, systemwide directory), and all existing
226 configuration files in the list will be read. A single
227 filename may also be given.
228 """
Walter Dörwald65230a22002-06-03 15:58:32 +0000229 if isinstance(filenames, basestring):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000230 filenames = [filenames]
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000231 for filename in filenames:
232 try:
233 fp = open(filename)
234 except IOError:
235 continue
236 self.__read(fp, filename)
Fred Drake2438a481999-10-04 18:11:56 +0000237 fp.close()
Guido van Rossum3d209861997-12-09 16:10:31 +0000238
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000239 def readfp(self, fp, filename=None):
240 """Like read() but the argument must be a file-like object.
241
242 The `fp' argument must have a `readline' method. Optional
243 second argument is the `filename', which if not given, is
244 taken from fp.name. If fp has no `name' attribute, `<???>' is
245 used.
246
247 """
248 if filename is None:
249 try:
250 filename = fp.name
251 except AttributeError:
252 filename = '<???>'
253 self.__read(fp, filename)
254
Guido van Rossume6506e71999-01-26 19:29:25 +0000255 def get(self, section, option, raw=0, vars=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000256 """Get an option value for a given section.
Guido van Rossum3d209861997-12-09 16:10:31 +0000257
Barry Warsawf09f6a51999-01-26 22:01:37 +0000258 All % interpolations are expanded in the return values, based on the
259 defaults passed into the constructor, unless the optional argument
260 `raw' is true. Additional substitutions may be provided using the
261 `vars' argument, which must be a dictionary whose contents overrides
262 any pre-existing defaults.
Guido van Rossum3d209861997-12-09 16:10:31 +0000263
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000264 The section DEFAULT is special.
265 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000266 d = self.__defaults.copy()
Fred Drakec2ff9052002-09-27 15:33:11 +0000267 try:
268 d.update(self.__sections[section])
269 except KeyError:
270 if section != DEFAULTSECT:
271 raise NoSectionError(section)
Guido van Rossume6506e71999-01-26 19:29:25 +0000272 # Update with the entry specific variables
Raymond Hettinger0f4940c2002-06-01 00:57:55 +0000273 if vars is not None:
Guido van Rossume6506e71999-01-26 19:29:25 +0000274 d.update(vars)
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000275 option = self.optionxform(option)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000276 try:
Fred Drakec2ff9052002-09-27 15:33:11 +0000277 value = d[option]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000278 except KeyError:
279 raise NoOptionError(option, section)
Fred Drake2a37f9f2000-09-27 22:43:54 +0000280
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000281 if raw:
Fred Drakec2ff9052002-09-27 15:33:11 +0000282 return value
283 return self._interpolate(section, option, value, d)
Guido van Rossum3d209861997-12-09 16:10:31 +0000284
Fred Drake2ca041f2002-09-27 15:49:56 +0000285 def items(self, section, raw=0, vars=None):
286 """Return a list of tuples with (name, value) for each option
287 in the section.
288
289 All % interpolations are expanded in the return values, based on the
290 defaults passed into the constructor, unless the optional argument
291 `raw' is true. Additional substitutions may be provided using the
292 `vars' argument, which must be a dictionary whose contents overrides
293 any pre-existing defaults.
294
295 The section DEFAULT is special.
296 """
297 d = self.__defaults.copy()
298 try:
299 d.update(self.__sections[section])
300 except KeyError:
301 if section != DEFAULTSECT:
302 raise NoSectionError(section)
303 # Update with the entry specific variables
304 if vars:
305 d.update(vars)
306 if raw:
307 for option in self.options(section):
308 yield (option, d[option])
309 else:
310 for option in self.options(section):
311 yield (option,
312 self._interpolate(section, option, d[option], d))
313
Fred Drakec2ff9052002-09-27 15:33:11 +0000314 def _interpolate(self, section, option, rawval, vars):
Fred Drake2a37f9f2000-09-27 22:43:54 +0000315 # do the string interpolation
Fred Drakec2ff9052002-09-27 15:33:11 +0000316 value = rawval
317 depth = MAX_INTERPOLATION_DEPTH
318 while depth: # Loop through this until it's done
319 depth -= 1
320 if value.find("%(") != -1:
Guido van Rossume6506e71999-01-26 19:29:25 +0000321 try:
Fred Drakec2ff9052002-09-27 15:33:11 +0000322 value = value % vars
Guido van Rossume6506e71999-01-26 19:29:25 +0000323 except KeyError, key:
324 raise InterpolationError(key, option, section, rawval)
325 else:
Fred Drake2a37f9f2000-09-27 22:43:54 +0000326 break
Fred Drakec2ff9052002-09-27 15:33:11 +0000327 if value.find("%(") != -1:
Fred Drake2a37f9f2000-09-27 22:43:54 +0000328 raise InterpolationDepthError(option, section, rawval)
329 return value
Tim Peters88869f92001-01-14 23:36:06 +0000330
Guido van Rossum3d209861997-12-09 16:10:31 +0000331 def __get(self, section, conv, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000332 return conv(self.get(section, option))
Guido van Rossum3d209861997-12-09 16:10:31 +0000333
334 def getint(self, section, option):
Fred Draked451ec12002-04-26 02:29:55 +0000335 return self.__get(section, int, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000336
337 def getfloat(self, section, option):
Fred Draked451ec12002-04-26 02:29:55 +0000338 return self.__get(section, float, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000339
Fred Drakec2ff9052002-09-27 15:33:11 +0000340 _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
341 '0': False, 'no': False, 'false': False, 'off': False}
342
Guido van Rossum3d209861997-12-09 16:10:31 +0000343 def getboolean(self, section, option):
Tim Peterse0c446b2001-10-18 21:57:37 +0000344 v = self.get(section, option)
Fred Drakec2ff9052002-09-27 15:33:11 +0000345 if v.lower() not in self._boolean_states:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000346 raise ValueError, 'Not a boolean: %s' % v
Fred Drakec2ff9052002-09-27 15:33:11 +0000347 return self._boolean_states[v.lower()]
Guido van Rossum3d209861997-12-09 16:10:31 +0000348
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000349 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000350 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000351
Eric S. Raymond417c4892000-07-10 18:11:00 +0000352 def has_option(self, section, option):
353 """Check for the existence of a given option in a given section."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000354 if not section or section == DEFAULTSECT:
355 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000356 return option in self.__defaults
Fred Drakec2ff9052002-09-27 15:33:11 +0000357 elif section not in self.__sections:
Eric S. Raymond417c4892000-07-10 18:11:00 +0000358 return 0
359 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000360 option = self.optionxform(option)
Fred Drakec2ff9052002-09-27 15:33:11 +0000361 return (option in self.__sections[section]
362 or option in self.__defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000363
364 def set(self, section, option, value):
365 """Set an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000366 if not section or section == DEFAULTSECT:
Eric S. Raymond417c4892000-07-10 18:11:00 +0000367 sectdict = self.__defaults
368 else:
369 try:
370 sectdict = self.__sections[section]
371 except KeyError:
372 raise NoSectionError(section)
Fred Drakec2ff9052002-09-27 15:33:11 +0000373 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000374
375 def write(self, fp):
376 """Write an .ini-format representation of the configuration state."""
377 if self.__defaults:
Fred Drakec2ff9052002-09-27 15:33:11 +0000378 fp.write("[%s]\n" % DEFAULTSECT)
Eric S. Raymond649685a2000-07-14 14:28:22 +0000379 for (key, value) in self.__defaults.items():
Andrew M. Kuchling00824ed2002-03-08 18:08:47 +0000380 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000381 fp.write("\n")
Fred Drakec2ff9052002-09-27 15:33:11 +0000382 for section in self.__sections:
383 fp.write("[%s]\n" % section)
384 for (key, value) in self.__sections[section].items():
385 if key != "__name__":
386 fp.write("%s = %s\n" %
387 (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000388 fp.write("\n")
389
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000390 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000391 """Remove an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000392 if not section or section == DEFAULTSECT:
Eric S. Raymond649685a2000-07-14 14:28:22 +0000393 sectdict = self.__defaults
394 else:
395 try:
396 sectdict = self.__sections[section]
397 except KeyError:
398 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000399 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000400 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000401 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000402 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000403 return existed
404
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000405 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000406 """Remove a file section."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000407 existed = section in self.__sections
408 if existed:
Eric S. Raymond649685a2000-07-14 14:28:22 +0000409 del self.__sections[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000410 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000411
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000412 #
Fred Drakec2ff9052002-09-27 15:33:11 +0000413 # Regular expressions for parsing section headers and options.
414 #
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000415 SECTCRE = re.compile(
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000416 r'\[' # [
Fred Draked4df94b2001-02-14 15:24:17 +0000417 r'(?P<header>[^]]+)' # very permissive!
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000418 r'\]' # ]
419 )
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000420 OPTCRE = re.compile(
Fred Drake176916a2002-09-27 16:21:18 +0000421 r'(?P<option>[^:=\s][^:=]*)' # very permissive!
Fred Drakec2ff9052002-09-27 15:33:11 +0000422 r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000423 # followed by separator
424 # (either : or =), followed
425 # by any # space/tab
426 r'(?P<value>.*)$' # everything up to eol
427 )
428
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000429 def __read(self, fp, fpname):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000430 """Parse a sectioned setup file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000431
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000432 The sections in setup file contains a title line at the top,
433 indicated by a name in square brackets (`[]'), plus key/value
434 options lines, indicated by `name: value' format lines.
435 Continuation are represented by an embedded newline then
436 leading whitespace. Blank lines, lines beginning with a '#',
437 and just about everything else is ignored.
438 """
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000439 cursect = None # None, or a dictionary
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000440 optname = None
441 lineno = 0
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000442 e = None # None, or an exception
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000443 while 1:
444 line = fp.readline()
445 if not line:
446 break
447 lineno = lineno + 1
448 # comment or blank line?
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000449 if line.strip() == '' or line[0] in '#;':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000450 continue
Fred Drake176916a2002-09-27 16:21:18 +0000451 if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
452 # no leading whitespace
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000453 continue
454 # continuation line?
Fred Drakec2ff9052002-09-27 15:33:11 +0000455 if line[0].isspace() and cursect is not None and optname:
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000456 value = line.strip()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000457 if value:
Fred Drakec2ff9052002-09-27 15:33:11 +0000458 cursect[optname] = "%s\n%s" % (cursect[optname], value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000459 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000460 else:
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000461 # is it a section header?
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000462 mo = self.SECTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000463 if mo:
464 sectname = mo.group('header')
Raymond Hettinger54f02222002-06-01 14:18:47 +0000465 if sectname in self.__sections:
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000466 cursect = self.__sections[sectname]
467 elif sectname == DEFAULTSECT:
468 cursect = self.__defaults
469 else:
Barry Warsaw64462121998-08-06 18:48:41 +0000470 cursect = {'__name__': sectname}
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000471 self.__sections[sectname] = cursect
472 # So sections can't start with a continuation line
473 optname = None
474 # no section header in the file?
475 elif cursect is None:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000476 raise MissingSectionHeaderError(fpname, lineno, `line`)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000477 # an option line?
478 else:
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000479 mo = self.OPTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000480 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +0000481 optname, vi, optval = mo.group('option', 'vi', 'value')
Jeremy Hylton820314e2000-03-03 20:43:57 +0000482 if vi in ('=', ':') and ';' in optval:
Fred Drakec517b9b2000-02-28 20:59:03 +0000483 # ';' is a comment delimiter only if it follows
484 # a spacing character
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000485 pos = optval.find(';')
Fred Drakec2ff9052002-09-27 15:33:11 +0000486 if pos != -1 and optval[pos-1].isspace():
Fred Drakec517b9b2000-02-28 20:59:03 +0000487 optval = optval[:pos]
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000488 optval = optval.strip()
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000489 # allow empty values
490 if optval == '""':
491 optval = ''
Fred Drake176916a2002-09-27 16:21:18 +0000492 optname = self.optionxform(optname.rstrip())
Fred Drakec2ff9052002-09-27 15:33:11 +0000493 cursect[optname] = optval
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000494 else:
495 # a non-fatal parsing error occurred. set up the
496 # exception but keep going. the exception will be
497 # raised at the end of the file and will contain a
498 # list of all bogus lines
499 if not e:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000500 e = ParsingError(fpname)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000501 e.append(lineno, `line`)
502 # if any parsing errors occurred, raise an exception
503 if e:
504 raise e