blob: bdce25ef0d358189bf6539f6cc9985d96e4443a3 [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
73 remove_section(section)
Tim Peters88869f92001-01-14 23:36:06 +000074 remove the given file section and all its options
Eric S. Raymond649685a2000-07-14 14:28:22 +000075
76 remove_option(section, option)
Tim Peters88869f92001-01-14 23:36:06 +000077 remove the given option from the given section
Eric S. Raymond649685a2000-07-14 14:28:22 +000078
79 set(section, option, value)
80 set the given option
81
82 write(fp)
Tim Peters88869f92001-01-14 23:36:06 +000083 write the configuration state in .ini format
Guido van Rossum3d209861997-12-09 16:10:31 +000084"""
85
Martin v. Löwis339d0f72001-08-17 18:39:25 +000086import string, types
Barry Warsawbfa3f6b1998-07-01 20:41:12 +000087import re
Guido van Rossum3d209861997-12-09 16:10:31 +000088
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000089__all__ = ["NoSectionError","DuplicateSectionError","NoOptionError",
90 "InterpolationError","InterpolationDepthError","ParsingError",
91 "MissingSectionHeaderError","ConfigParser",
92 "MAX_INTERPOLATION_DEPTH"]
93
Guido van Rossum3d209861997-12-09 16:10:31 +000094DEFAULTSECT = "DEFAULT"
95
Fred Drake2a37f9f2000-09-27 22:43:54 +000096MAX_INTERPOLATION_DEPTH = 10
97
Guido van Rossum3d209861997-12-09 16:10:31 +000098
Tim Peters88869f92001-01-14 23:36:06 +000099
Guido van Rossum3d209861997-12-09 16:10:31 +0000100# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000101class Error(Exception):
Guido van Rossum3d209861997-12-09 16:10:31 +0000102 def __init__(self, msg=''):
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000103 self._msg = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000104 Exception.__init__(self, msg)
Guido van Rossum3d209861997-12-09 16:10:31 +0000105 def __repr__(self):
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000106 return self._msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000107 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000108
109class NoSectionError(Error):
110 def __init__(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000111 Error.__init__(self, 'No section: %s' % section)
112 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000113
114class DuplicateSectionError(Error):
115 def __init__(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000116 Error.__init__(self, "Section %s already exists" % section)
117 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000118
119class NoOptionError(Error):
120 def __init__(self, option, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000121 Error.__init__(self, "No option `%s' in section: %s" %
122 (option, section))
123 self.option = option
124 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000125
126class InterpolationError(Error):
Barry Warsaw64462121998-08-06 18:48:41 +0000127 def __init__(self, reference, option, section, rawval):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000128 Error.__init__(self,
Barry Warsaw64462121998-08-06 18:48:41 +0000129 "Bad value substitution:\n"
130 "\tsection: [%s]\n"
131 "\toption : %s\n"
132 "\tkey : %s\n"
133 "\trawval : %s\n"
134 % (section, option, reference, rawval))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000135 self.reference = reference
136 self.option = option
137 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000138
Fred Drake2a37f9f2000-09-27 22:43:54 +0000139class InterpolationDepthError(Error):
140 def __init__(self, option, section, rawval):
141 Error.__init__(self,
142 "Value interpolation too deeply recursive:\n"
143 "\tsection: [%s]\n"
144 "\toption : %s\n"
145 "\trawval : %s\n"
146 % (section, option, rawval))
147 self.option = option
148 self.section = section
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000149
150class ParsingError(Error):
151 def __init__(self, filename):
152 Error.__init__(self, 'File contains parsing errors: %s' % filename)
153 self.filename = filename
154 self.errors = []
155
156 def append(self, lineno, line):
157 self.errors.append((lineno, line))
158 self._msg = self._msg + '\n\t[line %2d]: %s' % (lineno, line)
159
Fred Drake2a37f9f2000-09-27 22:43:54 +0000160class MissingSectionHeaderError(ParsingError):
161 def __init__(self, filename, lineno, line):
162 Error.__init__(
163 self,
164 'File contains no section headers.\nfile: %s, line: %d\n%s' %
165 (filename, lineno, line))
166 self.filename = filename
167 self.lineno = lineno
168 self.line = line
169
Guido van Rossum3d209861997-12-09 16:10:31 +0000170
Tim Peters88869f92001-01-14 23:36:06 +0000171
Guido van Rossum3d209861997-12-09 16:10:31 +0000172class ConfigParser:
173 def __init__(self, defaults=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000174 self.__sections = {}
175 if defaults is None:
176 self.__defaults = {}
177 else:
178 self.__defaults = defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000179
180 def defaults(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000181 return self.__defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000182
183 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000184 """Return a list of section names, excluding [DEFAULT]"""
185 # self.__sections will never have [DEFAULT] in it
186 return self.__sections.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000187
188 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000189 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000190
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000191 Raise DuplicateSectionError if a section by the specified name
192 already exists.
193 """
194 if self.__sections.has_key(section):
195 raise DuplicateSectionError(section)
196 self.__sections[section] = {}
Guido van Rossum3d209861997-12-09 16:10:31 +0000197
198 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000199 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000200
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000201 The DEFAULT section is not acknowledged.
202 """
Fred Drake2a37f9f2000-09-27 22:43:54 +0000203 return section in self.sections()
Guido van Rossum3d209861997-12-09 16:10:31 +0000204
205 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000206 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000207 try:
208 opts = self.__sections[section].copy()
209 except KeyError:
210 raise NoSectionError(section)
211 opts.update(self.__defaults)
Fred Drake2a37f9f2000-09-27 22:43:54 +0000212 if opts.has_key('__name__'):
213 del opts['__name__']
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000214 return opts.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000215
216 def read(self, filenames):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000217 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000218
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000219 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000220 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000221 configuration file locations (e.g. current directory, user's
222 home directory, systemwide directory), and all existing
223 configuration files in the list will be read. A single
224 filename may also be given.
225 """
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000226 if type(filenames) in types.StringTypes:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000227 filenames = [filenames]
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000228 for filename in filenames:
229 try:
230 fp = open(filename)
231 except IOError:
232 continue
233 self.__read(fp, filename)
Fred Drake2438a481999-10-04 18:11:56 +0000234 fp.close()
Guido van Rossum3d209861997-12-09 16:10:31 +0000235
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000236 def readfp(self, fp, filename=None):
237 """Like read() but the argument must be a file-like object.
238
239 The `fp' argument must have a `readline' method. Optional
240 second argument is the `filename', which if not given, is
241 taken from fp.name. If fp has no `name' attribute, `<???>' is
242 used.
243
244 """
245 if filename is None:
246 try:
247 filename = fp.name
248 except AttributeError:
249 filename = '<???>'
250 self.__read(fp, filename)
251
Guido van Rossume6506e71999-01-26 19:29:25 +0000252 def get(self, section, option, raw=0, vars=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000253 """Get an option value for a given section.
Guido van Rossum3d209861997-12-09 16:10:31 +0000254
Barry Warsawf09f6a51999-01-26 22:01:37 +0000255 All % interpolations are expanded in the return values, based on the
256 defaults passed into the constructor, unless the optional argument
257 `raw' is true. Additional substitutions may be provided using the
258 `vars' argument, which must be a dictionary whose contents overrides
259 any pre-existing defaults.
Guido van Rossum3d209861997-12-09 16:10:31 +0000260
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000261 The section DEFAULT is special.
262 """
263 try:
264 sectdict = self.__sections[section].copy()
265 except KeyError:
266 if section == DEFAULTSECT:
267 sectdict = {}
268 else:
269 raise NoSectionError(section)
270 d = self.__defaults.copy()
271 d.update(sectdict)
Guido van Rossume6506e71999-01-26 19:29:25 +0000272 # Update with the entry specific variables
273 if vars:
274 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:
277 rawval = d[option]
278 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:
282 return rawval
Guido van Rossum3d209861997-12-09 16:10:31 +0000283
Fred Drake2a37f9f2000-09-27 22:43:54 +0000284 # do the string interpolation
Guido van Rossume6506e71999-01-26 19:29:25 +0000285 value = rawval # Make it a pretty variable name
Tim Peters88869f92001-01-14 23:36:06 +0000286 depth = 0
Guido van Rossum72ce8581999-02-12 14:13:10 +0000287 while depth < 10: # Loop through this until it's done
288 depth = depth + 1
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000289 if value.find("%(") >= 0:
Guido van Rossume6506e71999-01-26 19:29:25 +0000290 try:
291 value = value % d
292 except KeyError, key:
293 raise InterpolationError(key, option, section, rawval)
294 else:
Fred Drake2a37f9f2000-09-27 22:43:54 +0000295 break
296 if value.find("%(") >= 0:
297 raise InterpolationDepthError(option, section, rawval)
298 return value
Tim Peters88869f92001-01-14 23:36:06 +0000299
Guido van Rossum3d209861997-12-09 16:10:31 +0000300 def __get(self, section, conv, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000301 return conv(self.get(section, option))
Guido van Rossum3d209861997-12-09 16:10:31 +0000302
303 def getint(self, section, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000304 return self.__get(section, string.atoi, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000305
306 def getfloat(self, section, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000307 return self.__get(section, string.atof, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000308
309 def getboolean(self, section, option):
Guido van Rossumfb06f752001-10-04 19:58:46 +0000310 states = {'1': 1, 'yes': 1, 'true': 1, 'on': 1,
311 '0': 0, 'no': 0, 'false': 0, 'off': 0}
Tim Peterse0c446b2001-10-18 21:57:37 +0000312 v = self.get(section, option)
Guido van Rossumfb06f752001-10-04 19:58:46 +0000313 if not states.has_key(v.lower()):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000314 raise ValueError, 'Not a boolean: %s' % v
Guido van Rossumfb06f752001-10-04 19:58:46 +0000315 return states[v.lower()]
Guido van Rossum3d209861997-12-09 16:10:31 +0000316
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000317 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000318 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000319
Eric S. Raymond417c4892000-07-10 18:11:00 +0000320 def has_option(self, section, option):
321 """Check for the existence of a given option in a given section."""
322 if not section or section == "DEFAULT":
323 return self.__defaults.has_key(option)
324 elif not self.has_section(section):
325 return 0
326 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000327 option = self.optionxform(option)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000328 return self.__sections[section].has_key(option)
329
330 def set(self, section, option, value):
331 """Set an option."""
332 if not section or section == "DEFAULT":
333 sectdict = self.__defaults
334 else:
335 try:
336 sectdict = self.__sections[section]
337 except KeyError:
338 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000339 option = self.optionxform(option)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000340 sectdict[option] = value
341
342 def write(self, fp):
343 """Write an .ini-format representation of the configuration state."""
344 if self.__defaults:
345 fp.write("[DEFAULT]\n")
Eric S. Raymond649685a2000-07-14 14:28:22 +0000346 for (key, value) in self.__defaults.items():
Andrew M. Kuchling00824ed2002-03-08 18:08:47 +0000347 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000348 fp.write("\n")
349 for section in self.sections():
350 fp.write("[" + section + "]\n")
351 sectdict = self.__sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000352 for (key, value) in sectdict.items():
Eric S. Raymond417c4892000-07-10 18:11:00 +0000353 if key == "__name__":
354 continue
Andrew M. Kuchling00824ed2002-03-08 18:08:47 +0000355 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000356 fp.write("\n")
357
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000358 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000359 """Remove an option."""
360 if not section or section == "DEFAULT":
361 sectdict = self.__defaults
362 else:
363 try:
364 sectdict = self.__sections[section]
365 except KeyError:
366 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000367 option = self.optionxform(option)
Fred Drakeff4a23b2000-12-04 16:29:13 +0000368 existed = sectdict.has_key(option)
Eric S. Raymond649685a2000-07-14 14:28:22 +0000369 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000370 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000371 return existed
372
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000373 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000374 """Remove a file section."""
375 if self.__sections.has_key(section):
376 del self.__sections[section]
377 return 1
378 else:
379 return 0
380
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000381 #
382 # Regular expressions for parsing section headers and options. Note a
383 # slight semantic change from the previous version, because of the use
384 # of \w, _ is allowed in section header names.
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000385 SECTCRE = re.compile(
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000386 r'\[' # [
Fred Draked4df94b2001-02-14 15:24:17 +0000387 r'(?P<header>[^]]+)' # very permissive!
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000388 r'\]' # ]
389 )
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000390 OPTCRE = re.compile(
Fred Draked83bbbf2001-02-12 17:18:11 +0000391 r'(?P<option>[]\-[\w_.*,(){}]+)' # a lot of stuff found by IvL
Fred Drakec517b9b2000-02-28 20:59:03 +0000392 r'[ \t]*(?P<vi>[:=])[ \t]*' # any number of space/tab,
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000393 # followed by separator
394 # (either : or =), followed
395 # by any # space/tab
396 r'(?P<value>.*)$' # everything up to eol
397 )
398
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000399 def __read(self, fp, fpname):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000400 """Parse a sectioned setup file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000401
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000402 The sections in setup file contains a title line at the top,
403 indicated by a name in square brackets (`[]'), plus key/value
404 options lines, indicated by `name: value' format lines.
405 Continuation are represented by an embedded newline then
406 leading whitespace. Blank lines, lines beginning with a '#',
407 and just about everything else is ignored.
408 """
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000409 cursect = None # None, or a dictionary
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000410 optname = None
411 lineno = 0
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000412 e = None # None, or an exception
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000413 while 1:
414 line = fp.readline()
415 if not line:
416 break
417 lineno = lineno + 1
418 # comment or blank line?
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000419 if line.strip() == '' or line[0] in '#;':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000420 continue
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000421 if line.split()[0].lower() == 'rem' \
Fred Drakec517b9b2000-02-28 20:59:03 +0000422 and line[0] in "rR": # no leading whitespace
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000423 continue
424 # continuation line?
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000425 if line[0] in ' \t' and cursect is not None and optname:
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000426 value = line.strip()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000427 if value:
Fred Drakebeb67132001-07-06 17:22:48 +0000428 k = self.optionxform(optname)
429 cursect[k] = "%s\n%s" % (cursect[k], value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000430 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000431 else:
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000432 # is it a section header?
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000433 mo = self.SECTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000434 if mo:
435 sectname = mo.group('header')
436 if self.__sections.has_key(sectname):
437 cursect = self.__sections[sectname]
438 elif sectname == DEFAULTSECT:
439 cursect = self.__defaults
440 else:
Barry Warsaw64462121998-08-06 18:48:41 +0000441 cursect = {'__name__': sectname}
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000442 self.__sections[sectname] = cursect
443 # So sections can't start with a continuation line
444 optname = None
445 # no section header in the file?
446 elif cursect is None:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000447 raise MissingSectionHeaderError(fpname, lineno, `line`)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000448 # an option line?
449 else:
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000450 mo = self.OPTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000451 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +0000452 optname, vi, optval = mo.group('option', 'vi', 'value')
Jeremy Hylton820314e2000-03-03 20:43:57 +0000453 if vi in ('=', ':') and ';' in optval:
Fred Drakec517b9b2000-02-28 20:59:03 +0000454 # ';' is a comment delimiter only if it follows
455 # a spacing character
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000456 pos = optval.find(';')
Fred Drakec517b9b2000-02-28 20:59:03 +0000457 if pos and optval[pos-1] in string.whitespace:
458 optval = optval[:pos]
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000459 optval = optval.strip()
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000460 # allow empty values
461 if optval == '""':
462 optval = ''
Guido van Rossum41267362000-09-25 14:42:33 +0000463 cursect[self.optionxform(optname)] = optval
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000464 else:
465 # a non-fatal parsing error occurred. set up the
466 # exception but keep going. the exception will be
467 # raised at the end of the file and will contain a
468 # list of all bogus lines
469 if not e:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000470 e = ParsingError(fpname)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000471 e.append(lineno, `line`)
472 # if any parsing errors occurred, raise an exception
473 if e:
474 raise e