blob: 049373948b65e0e0fb59b807fc51bac51a00b7aa [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
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +000022ConfigParser -- responsible for parsing a list of
Guido van Rossum3d209861997-12-09 16:10:31 +000023 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;
Georg Brandl7eb4b7d2005-07-22 21:49:32 +000031 its 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
Fred Drake82903142004-05-18 04:24:02 +000048 are ignored. Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000049
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
Raymond Hettingere89b8e92009-03-03 05:00:37 +000090try:
91 from collections import OrderedDict as _default_dict
92except ImportError:
93 # fallback for setup.py which hasn't yet built _collections
94 _default_dict = dict
95
Barry Warsawbfa3f6b1998-07-01 20:41:12 +000096import re
Guido van Rossum3d209861997-12-09 16:10:31 +000097
Fred Drake8d5dd982002-12-30 23:51:45 +000098__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
99 "InterpolationError", "InterpolationDepthError",
100 "InterpolationSyntaxError", "ParsingError",
David Goodger1cbf2062004-10-03 15:55:09 +0000101 "MissingSectionHeaderError",
102 "ConfigParser", "SafeConfigParser", "RawConfigParser",
Fred Drakec2ff9052002-09-27 15:33:11 +0000103 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +0000104
Guido van Rossum3d209861997-12-09 16:10:31 +0000105DEFAULTSECT = "DEFAULT"
106
Fred Drake2a37f9f2000-09-27 22:43:54 +0000107MAX_INTERPOLATION_DEPTH = 10
108
Guido van Rossum3d209861997-12-09 16:10:31 +0000109
Tim Peters88869f92001-01-14 23:36:06 +0000110
Guido van Rossum3d209861997-12-09 16:10:31 +0000111# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000112class Error(Exception):
Fred Drake8d5dd982002-12-30 23:51:45 +0000113 """Base class for ConfigParser exceptions."""
114
Brett Cannon229cee22007-05-05 01:34:02 +0000115 def _get_message(self):
116 """Getter for 'message'; needed only to override deprecation in
117 BaseException."""
118 return self.__message
119
120 def _set_message(self, value):
121 """Setter for 'message'; needed only to override deprecation in
122 BaseException."""
123 self.__message = value
124
125 # BaseException.message has been deprecated since Python 2.6. To prevent
126 # DeprecationWarning from popping up over this pre-existing attribute, use
127 # a new property that takes lookup precedence.
128 message = property(_get_message, _set_message)
129
Guido van Rossum3d209861997-12-09 16:10:31 +0000130 def __init__(self, msg=''):
Fred Drakee2c64912002-12-31 17:23:27 +0000131 self.message = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000132 Exception.__init__(self, msg)
Fred Drake8d5dd982002-12-30 23:51:45 +0000133
Guido van Rossum3d209861997-12-09 16:10:31 +0000134 def __repr__(self):
Fred Drakee2c64912002-12-31 17:23:27 +0000135 return self.message
Fred Drake8d5dd982002-12-30 23:51:45 +0000136
Łukasz Langa631c2582012-01-20 17:02:08 +0100137 def __reduce__(self):
138 return self.__class__, (self.message,)
139
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000140 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000141
142class NoSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000143 """Raised when no section matches a requested option."""
144
Guido van Rossum3d209861997-12-09 16:10:31 +0000145 def __init__(self, section):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000146 Error.__init__(self, 'No section: %r' % (section,))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000147 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000148
Łukasz Langa631c2582012-01-20 17:02:08 +0100149 def __reduce__(self):
150 return self.__class__, (self.section,)
151
Guido van Rossum3d209861997-12-09 16:10:31 +0000152class DuplicateSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000153 """Raised when a section is multiply-created."""
154
Guido van Rossum3d209861997-12-09 16:10:31 +0000155 def __init__(self, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000156 Error.__init__(self, "Section %r already exists" % section)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000157 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000158
Łukasz Langa631c2582012-01-20 17:02:08 +0100159 def __reduce__(self):
160 return self.__class__, (self.section,)
161
Guido van Rossum3d209861997-12-09 16:10:31 +0000162class NoOptionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000163 """A requested option was not found."""
164
Guido van Rossum3d209861997-12-09 16:10:31 +0000165 def __init__(self, option, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000166 Error.__init__(self, "No option %r in section: %r" %
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000167 (option, section))
168 self.option = option
169 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000170
Łukasz Langa631c2582012-01-20 17:02:08 +0100171 def __reduce__(self):
172 return self.__class__, (self.option, self.section)
173
Guido van Rossum3d209861997-12-09 16:10:31 +0000174class InterpolationError(Error):
Fred Drakee2c64912002-12-31 17:23:27 +0000175 """Base class for interpolation-related exceptions."""
Fred Drake8d5dd982002-12-30 23:51:45 +0000176
Fred Drakee2c64912002-12-31 17:23:27 +0000177 def __init__(self, option, section, msg):
178 Error.__init__(self, msg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000179 self.option = option
180 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000181
Łukasz Langa631c2582012-01-20 17:02:08 +0100182 def __reduce__(self):
183 return self.__class__, (self.option, self.section, self.message)
184
Fred Drakee2c64912002-12-31 17:23:27 +0000185class InterpolationMissingOptionError(InterpolationError):
186 """A string substitution required a setting which was not available."""
187
188 def __init__(self, option, section, rawval, reference):
189 msg = ("Bad value substitution:\n"
190 "\tsection: [%s]\n"
191 "\toption : %s\n"
192 "\tkey : %s\n"
193 "\trawval : %s\n"
194 % (section, option, reference, rawval))
195 InterpolationError.__init__(self, option, section, msg)
196 self.reference = reference
Łukasz Langa631c2582012-01-20 17:02:08 +0100197 self._rawval = rawval
198
199 def __reduce__(self):
200 return self.__class__, (self.option, self.section, self._rawval,
201 self.reference)
Fred Drakee2c64912002-12-31 17:23:27 +0000202
203class InterpolationSyntaxError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000204 """Raised when the source text into which substitutions are made
205 does not conform to the required syntax."""
Neal Norwitzce1d9442002-12-30 23:38:47 +0000206
Fred Drakee2c64912002-12-31 17:23:27 +0000207class InterpolationDepthError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000208 """Raised when substitutions are nested too deeply."""
209
Fred Drake2a37f9f2000-09-27 22:43:54 +0000210 def __init__(self, option, section, rawval):
Fred Drakee2c64912002-12-31 17:23:27 +0000211 msg = ("Value interpolation too deeply recursive:\n"
212 "\tsection: [%s]\n"
213 "\toption : %s\n"
214 "\trawval : %s\n"
215 % (section, option, rawval))
216 InterpolationError.__init__(self, option, section, msg)
Łukasz Langa631c2582012-01-20 17:02:08 +0100217 self._rawval = rawval
218
219 def __reduce__(self):
220 return self.__class__, (self.option, self.section, self._rawval)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000221
222class ParsingError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000223 """Raised when a configuration file does not follow legal syntax."""
224
Łukasz Langa631c2582012-01-20 17:02:08 +0100225 def __init__(self, filename, _errors=[]):
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000226 Error.__init__(self, 'File contains parsing errors: %s' % filename)
227 self.filename = filename
228 self.errors = []
Łukasz Langa631c2582012-01-20 17:02:08 +0100229 for lineno, line in _errors:
230 self.append(lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000231
232 def append(self, lineno, line):
233 self.errors.append((lineno, line))
Fred Drakee2c64912002-12-31 17:23:27 +0000234 self.message += '\n\t[line %2d]: %s' % (lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000235
Łukasz Langa631c2582012-01-20 17:02:08 +0100236 def __reduce__(self):
237 return self.__class__, (self.filename, self.errors)
238
Fred Drake2a37f9f2000-09-27 22:43:54 +0000239class MissingSectionHeaderError(ParsingError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000240 """Raised when a key-value pair is found before any section header."""
241
Fred Drake2a37f9f2000-09-27 22:43:54 +0000242 def __init__(self, filename, lineno, line):
243 Error.__init__(
244 self,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000245 'File contains no section headers.\nfile: %s, line: %d\n%r' %
Fred Drake2a37f9f2000-09-27 22:43:54 +0000246 (filename, lineno, line))
247 self.filename = filename
248 self.lineno = lineno
249 self.line = line
250
Łukasz Langa631c2582012-01-20 17:02:08 +0100251 def __reduce__(self):
252 return self.__class__, (self.filename, self.lineno, self.line)
253
Guido van Rossum3d209861997-12-09 16:10:31 +0000254
Fred Drakefce65572002-10-25 18:08:18 +0000255class RawConfigParser:
Fred Drakecc43b562010-02-19 05:24:30 +0000256 def __init__(self, defaults=None, dict_type=_default_dict,
257 allow_no_value=False):
Martin v. Löwisa00bcac2006-12-03 12:01:53 +0000258 self._dict = dict_type
259 self._sections = self._dict()
260 self._defaults = self._dict()
Fred Drakecc43b562010-02-19 05:24:30 +0000261 if allow_no_value:
262 self._optcre = self.OPTCRE_NV
263 else:
264 self._optcre = self.OPTCRE
David Goodger68a1abd2004-10-03 15:40:25 +0000265 if defaults:
266 for key, value in defaults.items():
267 self._defaults[self.optionxform(key)] = value
Guido van Rossum3d209861997-12-09 16:10:31 +0000268
269 def defaults(self):
Fred Drakefce65572002-10-25 18:08:18 +0000270 return self._defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000271
272 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000273 """Return a list of section names, excluding [DEFAULT]"""
Fred Drakefce65572002-10-25 18:08:18 +0000274 # self._sections will never have [DEFAULT] in it
275 return self._sections.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000276
277 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000278 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000279
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000280 Raise DuplicateSectionError if a section by the specified name
Facundo Batistab12f0b52008-02-23 12:46:10 +0000281 already exists. Raise ValueError if name is DEFAULT or any of it's
282 case-insensitive variants.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000283 """
Facundo Batistab12f0b52008-02-23 12:46:10 +0000284 if section.lower() == "default":
285 raise ValueError, 'Invalid section name: %s' % section
286
Fred Drakefce65572002-10-25 18:08:18 +0000287 if section in self._sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000288 raise DuplicateSectionError(section)
Martin v. Löwisa00bcac2006-12-03 12:01:53 +0000289 self._sections[section] = self._dict()
Guido van Rossum3d209861997-12-09 16:10:31 +0000290
291 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000292 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000293
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000294 The DEFAULT section is not acknowledged.
295 """
Fred Drakefce65572002-10-25 18:08:18 +0000296 return section in self._sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000297
298 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000299 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000300 try:
Fred Drakefce65572002-10-25 18:08:18 +0000301 opts = self._sections[section].copy()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000302 except KeyError:
303 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000304 opts.update(self._defaults)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000305 if '__name__' in opts:
Fred Drake2a37f9f2000-09-27 22:43:54 +0000306 del opts['__name__']
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000307 return opts.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000308
309 def read(self, filenames):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000310 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000311
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000312 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000313 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000314 configuration file locations (e.g. current directory, user's
315 home directory, systemwide directory), and all existing
316 configuration files in the list will be read. A single
317 filename may also be given.
Fred Drake82903142004-05-18 04:24:02 +0000318
319 Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000320 """
Walter Dörwald65230a22002-06-03 15:58:32 +0000321 if isinstance(filenames, basestring):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000322 filenames = [filenames]
Fred Drake82903142004-05-18 04:24:02 +0000323 read_ok = []
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000324 for filename in filenames:
325 try:
326 fp = open(filename)
327 except IOError:
328 continue
Fred Drakefce65572002-10-25 18:08:18 +0000329 self._read(fp, filename)
Fred Drake2438a481999-10-04 18:11:56 +0000330 fp.close()
Fred Drake82903142004-05-18 04:24:02 +0000331 read_ok.append(filename)
332 return read_ok
Guido van Rossum3d209861997-12-09 16:10:31 +0000333
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000334 def readfp(self, fp, filename=None):
335 """Like read() but the argument must be a file-like object.
336
337 The `fp' argument must have a `readline' method. Optional
338 second argument is the `filename', which if not given, is
339 taken from fp.name. If fp has no `name' attribute, `<???>' is
340 used.
341
342 """
343 if filename is None:
344 try:
345 filename = fp.name
346 except AttributeError:
347 filename = '<???>'
Fred Drakefce65572002-10-25 18:08:18 +0000348 self._read(fp, filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000349
Fred Drakefce65572002-10-25 18:08:18 +0000350 def get(self, section, option):
351 opt = self.optionxform(option)
352 if section not in self._sections:
Fred Drakec2ff9052002-09-27 15:33:11 +0000353 if section != DEFAULTSECT:
354 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000355 if opt in self._defaults:
356 return self._defaults[opt]
357 else:
358 raise NoOptionError(option, section)
359 elif opt in self._sections[section]:
360 return self._sections[section][opt]
361 elif opt in self._defaults:
362 return self._defaults[opt]
363 else:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000364 raise NoOptionError(option, section)
Fred Drake2a37f9f2000-09-27 22:43:54 +0000365
Fred Drakefce65572002-10-25 18:08:18 +0000366 def items(self, section):
Fred Drake2ca041f2002-09-27 15:49:56 +0000367 try:
Fred Drakefce65572002-10-25 18:08:18 +0000368 d2 = self._sections[section]
Fred Drake2ca041f2002-09-27 15:49:56 +0000369 except KeyError:
370 if section != DEFAULTSECT:
371 raise NoSectionError(section)
Martin v. Löwisa00bcac2006-12-03 12:01:53 +0000372 d2 = self._dict()
Fred Drakefce65572002-10-25 18:08:18 +0000373 d = self._defaults.copy()
374 d.update(d2)
Fred Drakedf393bd2002-10-25 20:41:30 +0000375 if "__name__" in d:
376 del d["__name__"]
Fred Drakefce65572002-10-25 18:08:18 +0000377 return d.items()
Fred Drake2ca041f2002-09-27 15:49:56 +0000378
Fred Drakefce65572002-10-25 18:08:18 +0000379 def _get(self, section, conv, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000380 return conv(self.get(section, option))
Guido van Rossum3d209861997-12-09 16:10:31 +0000381
382 def getint(self, section, option):
Fred Drakefce65572002-10-25 18:08:18 +0000383 return self._get(section, int, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000384
385 def getfloat(self, section, option):
Fred Drakefce65572002-10-25 18:08:18 +0000386 return self._get(section, float, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000387
Fred Drakec2ff9052002-09-27 15:33:11 +0000388 _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
389 '0': False, 'no': False, 'false': False, 'off': False}
390
Guido van Rossum3d209861997-12-09 16:10:31 +0000391 def getboolean(self, section, option):
Tim Peterse0c446b2001-10-18 21:57:37 +0000392 v = self.get(section, option)
Fred Drakec2ff9052002-09-27 15:33:11 +0000393 if v.lower() not in self._boolean_states:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000394 raise ValueError, 'Not a boolean: %s' % v
Fred Drakec2ff9052002-09-27 15:33:11 +0000395 return self._boolean_states[v.lower()]
Guido van Rossum3d209861997-12-09 16:10:31 +0000396
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000397 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000398 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000399
Eric S. Raymond417c4892000-07-10 18:11:00 +0000400 def has_option(self, section, option):
401 """Check for the existence of a given option in a given section."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000402 if not section or section == DEFAULTSECT:
403 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000404 return option in self._defaults
405 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000406 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000407 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000408 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000409 return (option in self._sections[section]
410 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000411
Fred Drakecc43b562010-02-19 05:24:30 +0000412 def set(self, section, option, value=None):
Eric S. Raymond417c4892000-07-10 18:11:00 +0000413 """Set an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000414 if not section or section == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000415 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000416 else:
417 try:
Fred Drakefce65572002-10-25 18:08:18 +0000418 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000419 except KeyError:
420 raise NoSectionError(section)
Fred Drakec2ff9052002-09-27 15:33:11 +0000421 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000422
423 def write(self, fp):
424 """Write an .ini-format representation of the configuration state."""
Fred Drakefce65572002-10-25 18:08:18 +0000425 if self._defaults:
Fred Drakec2ff9052002-09-27 15:33:11 +0000426 fp.write("[%s]\n" % DEFAULTSECT)
Fred Drakefce65572002-10-25 18:08:18 +0000427 for (key, value) in self._defaults.items():
Andrew M. Kuchling00824ed2002-03-08 18:08:47 +0000428 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000429 fp.write("\n")
Fred Drakefce65572002-10-25 18:08:18 +0000430 for section in self._sections:
Fred Drakec2ff9052002-09-27 15:33:11 +0000431 fp.write("[%s]\n" % section)
Fred Drakefce65572002-10-25 18:08:18 +0000432 for (key, value) in self._sections[section].items():
Brian Curtine4334b42010-07-26 02:30:15 +0000433 if key == "__name__":
434 continue
Fred Drakea1e627d2010-09-03 03:55:50 +0000435 if (value is not None) or (self._optcre == self.OPTCRE):
Brian Curtine4334b42010-07-26 02:30:15 +0000436 key = " = ".join((key, str(value).replace('\n', '\n\t')))
437 fp.write("%s\n" % (key))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000438 fp.write("\n")
439
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000440 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000441 """Remove an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000442 if not section or section == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000443 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000444 else:
445 try:
Fred Drakefce65572002-10-25 18:08:18 +0000446 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000447 except KeyError:
448 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000449 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000450 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000451 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000452 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000453 return existed
454
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000455 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000456 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000457 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000458 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000459 del self._sections[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000460 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000461
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000462 #
Fred Drakec2ff9052002-09-27 15:33:11 +0000463 # Regular expressions for parsing section headers and options.
464 #
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000465 SECTCRE = re.compile(
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000466 r'\[' # [
Fred Draked4df94b2001-02-14 15:24:17 +0000467 r'(?P<header>[^]]+)' # very permissive!
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000468 r'\]' # ]
469 )
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000470 OPTCRE = re.compile(
Fred Drake176916a2002-09-27 16:21:18 +0000471 r'(?P<option>[^:=\s][^:=]*)' # very permissive!
Fred Drakec2ff9052002-09-27 15:33:11 +0000472 r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000473 # followed by separator
474 # (either : or =), followed
475 # by any # space/tab
476 r'(?P<value>.*)$' # everything up to eol
477 )
Fred Drakecc43b562010-02-19 05:24:30 +0000478 OPTCRE_NV = re.compile(
479 r'(?P<option>[^:=\s][^:=]*)' # very permissive!
480 r'\s*(?:' # any number of space/tab,
481 r'(?P<vi>[:=])\s*' # optionally followed by
482 # separator (either : or
483 # =), followed by any #
484 # space/tab
485 r'(?P<value>.*))?$' # everything up to eol
486 )
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000487
Fred Drakefce65572002-10-25 18:08:18 +0000488 def _read(self, fp, fpname):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000489 """Parse a sectioned setup file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000490
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000491 The sections in setup file contains a title line at the top,
492 indicated by a name in square brackets (`[]'), plus key/value
493 options lines, indicated by `name: value' format lines.
Andrew M. Kuchling9050a512002-11-06 14:51:20 +0000494 Continuations are represented by an embedded newline then
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000495 leading whitespace. Blank lines, lines beginning with a '#',
Andrew M. Kuchling9050a512002-11-06 14:51:20 +0000496 and just about everything else are ignored.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000497 """
Brian Curtine4334b42010-07-26 02:30:15 +0000498 cursect = None # None, or a dictionary
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000499 optname = None
500 lineno = 0
Brian Curtine4334b42010-07-26 02:30:15 +0000501 e = None # None, or an exception
Neal Norwitzf680cc42002-12-17 01:56:47 +0000502 while True:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000503 line = fp.readline()
504 if not line:
505 break
506 lineno = lineno + 1
507 # comment or blank line?
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000508 if line.strip() == '' or line[0] in '#;':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000509 continue
Fred Drake176916a2002-09-27 16:21:18 +0000510 if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
511 # no leading whitespace
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000512 continue
513 # continuation line?
Fred Drakec2ff9052002-09-27 15:33:11 +0000514 if line[0].isspace() and cursect is not None and optname:
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000515 value = line.strip()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000516 if value:
Brian Curtine4334b42010-07-26 02:30:15 +0000517 cursect[optname].append(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000518 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000519 else:
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000520 # is it a section header?
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000521 mo = self.SECTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000522 if mo:
523 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +0000524 if sectname in self._sections:
525 cursect = self._sections[sectname]
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000526 elif sectname == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000527 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000528 else:
Martin v. Löwisa00bcac2006-12-03 12:01:53 +0000529 cursect = self._dict()
530 cursect['__name__'] = sectname
Fred Drakefce65572002-10-25 18:08:18 +0000531 self._sections[sectname] = cursect
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000532 # So sections can't start with a continuation line
533 optname = None
534 # no section header in the file?
535 elif cursect is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000536 raise MissingSectionHeaderError(fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000537 # an option line?
538 else:
Fred Drakecc43b562010-02-19 05:24:30 +0000539 mo = self._optcre.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000540 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +0000541 optname, vi, optval = mo.group('option', 'vi', 'value')
Brian Curtine4334b42010-07-26 02:30:15 +0000542 optname = self.optionxform(optname.rstrip())
Fred Drakecc43b562010-02-19 05:24:30 +0000543 # This check is fine because the OPTCRE cannot
544 # match if it would set optval to None
545 if optval is not None:
546 if vi in ('=', ':') and ';' in optval:
547 # ';' is a comment delimiter only if it follows
548 # a spacing character
549 pos = optval.find(';')
550 if pos != -1 and optval[pos-1].isspace():
551 optval = optval[:pos]
552 optval = optval.strip()
Brian Curtine4334b42010-07-26 02:30:15 +0000553 # allow empty values
554 if optval == '""':
555 optval = ''
556 cursect[optname] = [optval]
557 else:
558 # valueless option handling
559 cursect[optname] = optval
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000560 else:
561 # a non-fatal parsing error occurred. set up the
562 # exception but keep going. the exception will be
563 # raised at the end of the file and will contain a
564 # list of all bogus lines
565 if not e:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000566 e = ParsingError(fpname)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000567 e.append(lineno, repr(line))
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000568 # if any parsing errors occurred, raise an exception
569 if e:
570 raise e
Fred Drakefce65572002-10-25 18:08:18 +0000571
Brian Curtine4334b42010-07-26 02:30:15 +0000572 # join the multi-line values collected while reading
573 all_sections = [self._defaults]
574 all_sections.extend(self._sections.values())
575 for options in all_sections:
576 for name, val in options.items():
577 if isinstance(val, list):
578 options[name] = '\n'.join(val)
Fred Drakefce65572002-10-25 18:08:18 +0000579
Raymond Hettingerd57b4d32011-02-02 08:37:11 +0000580import UserDict as _UserDict
581
582class _Chainmap(_UserDict.DictMixin):
583 """Combine multiple mappings for successive lookups.
584
585 For example, to emulate Python's normal lookup sequence:
586
587 import __builtin__
588 pylookup = _Chainmap(locals(), globals(), vars(__builtin__))
589 """
590
591 def __init__(self, *maps):
592 self._maps = maps
593
594 def __getitem__(self, key):
595 for mapping in self._maps:
596 try:
597 return mapping[key]
598 except KeyError:
599 pass
600 raise KeyError(key)
601
602 def keys(self):
603 result = []
604 seen = set()
Raymond Hettinger3ea52242011-08-09 12:07:15 -0700605 for mapping in self._maps:
Raymond Hettingerd57b4d32011-02-02 08:37:11 +0000606 for key in mapping:
607 if key not in seen:
608 result.append(key)
609 seen.add(key)
610 return result
611
Fred Drakefce65572002-10-25 18:08:18 +0000612class ConfigParser(RawConfigParser):
613
Neal Norwitzf680cc42002-12-17 01:56:47 +0000614 def get(self, section, option, raw=False, vars=None):
Fred Drakefce65572002-10-25 18:08:18 +0000615 """Get an option value for a given section.
616
Georg Brandld070cc52010-08-01 21:06:46 +0000617 If `vars' is provided, it must be a dictionary. The option is looked up
618 in `vars' (if provided), `section', and in `defaults' in that order.
619
620 All % interpolations are expanded in the return values, unless the
621 optional argument `raw' is true. Values for interpolation keys are
622 looked up in the same manner as the option.
Fred Drakefce65572002-10-25 18:08:18 +0000623
624 The section DEFAULT is special.
625 """
Raymond Hettingerd57b4d32011-02-02 08:37:11 +0000626 sectiondict = {}
Fred Drakefce65572002-10-25 18:08:18 +0000627 try:
Raymond Hettingerd57b4d32011-02-02 08:37:11 +0000628 sectiondict = self._sections[section]
Fred Drakefce65572002-10-25 18:08:18 +0000629 except KeyError:
630 if section != DEFAULTSECT:
631 raise NoSectionError(section)
632 # Update with the entry specific variables
Raymond Hettingerd57b4d32011-02-02 08:37:11 +0000633 vardict = {}
David Goodger68a1abd2004-10-03 15:40:25 +0000634 if vars:
635 for key, value in vars.items():
Raymond Hettingerd57b4d32011-02-02 08:37:11 +0000636 vardict[self.optionxform(key)] = value
637 d = _Chainmap(vardict, sectiondict, self._defaults)
Fred Drakefce65572002-10-25 18:08:18 +0000638 option = self.optionxform(option)
639 try:
640 value = d[option]
641 except KeyError:
642 raise NoOptionError(option, section)
643
Fred Drakecc43b562010-02-19 05:24:30 +0000644 if raw or value is None:
Fred Drakefce65572002-10-25 18:08:18 +0000645 return value
646 else:
647 return self._interpolate(section, option, value, d)
648
Neal Norwitzf680cc42002-12-17 01:56:47 +0000649 def items(self, section, raw=False, vars=None):
Fred Drakefce65572002-10-25 18:08:18 +0000650 """Return a list of tuples with (name, value) for each option
651 in the section.
652
653 All % interpolations are expanded in the return values, based on the
654 defaults passed into the constructor, unless the optional argument
655 `raw' is true. Additional substitutions may be provided using the
656 `vars' argument, which must be a dictionary whose contents overrides
657 any pre-existing defaults.
658
659 The section DEFAULT is special.
660 """
661 d = self._defaults.copy()
662 try:
663 d.update(self._sections[section])
664 except KeyError:
665 if section != DEFAULTSECT:
666 raise NoSectionError(section)
667 # Update with the entry specific variables
668 if vars:
David Goodger68a1abd2004-10-03 15:40:25 +0000669 for key, value in vars.items():
670 d[self.optionxform(key)] = value
Fred Drakedf393bd2002-10-25 20:41:30 +0000671 options = d.keys()
672 if "__name__" in options:
673 options.remove("__name__")
Fred Drakefce65572002-10-25 18:08:18 +0000674 if raw:
Fred Drake8c4da532003-10-21 16:45:00 +0000675 return [(option, d[option])
676 for option in options]
Fred Drakefce65572002-10-25 18:08:18 +0000677 else:
Fred Drake8c4da532003-10-21 16:45:00 +0000678 return [(option, self._interpolate(section, option, d[option], d))
679 for option in options]
Fred Drakefce65572002-10-25 18:08:18 +0000680
681 def _interpolate(self, section, option, rawval, vars):
682 # do the string interpolation
683 value = rawval
Tim Peters230a60c2002-11-09 05:08:07 +0000684 depth = MAX_INTERPOLATION_DEPTH
Fred Drakefce65572002-10-25 18:08:18 +0000685 while depth: # Loop through this until it's done
686 depth -= 1
Fred Drakecc43b562010-02-19 05:24:30 +0000687 if value and "%(" in value:
Fred Drakebc12b012004-05-18 02:25:51 +0000688 value = self._KEYCRE.sub(self._interpolation_replace, value)
Fred Drakefce65572002-10-25 18:08:18 +0000689 try:
690 value = value % vars
Fred Drake00dc5a92002-12-31 06:55:41 +0000691 except KeyError, e:
Fred Drakee2c64912002-12-31 17:23:27 +0000692 raise InterpolationMissingOptionError(
Brett Cannon97b1fb62008-08-02 03:37:50 +0000693 option, section, rawval, e.args[0])
Fred Drakefce65572002-10-25 18:08:18 +0000694 else:
695 break
Fred Drakecc43b562010-02-19 05:24:30 +0000696 if value and "%(" in value:
Fred Drakefce65572002-10-25 18:08:18 +0000697 raise InterpolationDepthError(option, section, rawval)
698 return value
Fred Drake0eebd5c2002-10-25 21:52:00 +0000699
Fred Drakebc12b012004-05-18 02:25:51 +0000700 _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
701
702 def _interpolation_replace(self, match):
703 s = match.group(1)
704 if s is None:
705 return match.group()
706 else:
707 return "%%(%s)s" % self.optionxform(s)
708
Fred Drake0eebd5c2002-10-25 21:52:00 +0000709
710class SafeConfigParser(ConfigParser):
711
712 def _interpolate(self, section, option, rawval, vars):
713 # do the string interpolation
714 L = []
715 self._interpolate_some(option, L, rawval, section, vars, 1)
716 return ''.join(L)
717
Georg Brandl92a6bae2007-03-13 17:43:32 +0000718 _interpvar_re = re.compile(r"%\(([^)]+)\)s")
Fred Drake0eebd5c2002-10-25 21:52:00 +0000719
720 def _interpolate_some(self, option, accum, rest, section, map, depth):
721 if depth > MAX_INTERPOLATION_DEPTH:
722 raise InterpolationDepthError(option, section, rest)
723 while rest:
724 p = rest.find("%")
725 if p < 0:
726 accum.append(rest)
727 return
728 if p > 0:
729 accum.append(rest[:p])
730 rest = rest[p:]
731 # p is no longer used
732 c = rest[1:2]
733 if c == "%":
734 accum.append("%")
735 rest = rest[2:]
736 elif c == "(":
Georg Brandl92a6bae2007-03-13 17:43:32 +0000737 m = self._interpvar_re.match(rest)
Fred Drake0eebd5c2002-10-25 21:52:00 +0000738 if m is None:
Neal Norwitz10f30182003-06-29 04:23:35 +0000739 raise InterpolationSyntaxError(option, section,
740 "bad interpolation variable reference %r" % rest)
Fred Drakebc12b012004-05-18 02:25:51 +0000741 var = self.optionxform(m.group(1))
Fred Drake0eebd5c2002-10-25 21:52:00 +0000742 rest = rest[m.end():]
743 try:
744 v = map[var]
745 except KeyError:
Fred Drakee2c64912002-12-31 17:23:27 +0000746 raise InterpolationMissingOptionError(
747 option, section, rest, var)
Fred Drake0eebd5c2002-10-25 21:52:00 +0000748 if "%" in v:
749 self._interpolate_some(option, accum, v,
750 section, map, depth + 1)
751 else:
752 accum.append(v)
753 else:
754 raise InterpolationSyntaxError(
Neal Norwitz10f30182003-06-29 04:23:35 +0000755 option, section,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000756 "'%%' must be followed by '%%' or '(', found: %r" % (rest,))
David Goodger1cbf2062004-10-03 15:55:09 +0000757
Fred Drakecc43b562010-02-19 05:24:30 +0000758 def set(self, section, option, value=None):
David Goodger1cbf2062004-10-03 15:55:09 +0000759 """Set an option. Extend ConfigParser.set: check for string values."""
Fred Drakecc43b562010-02-19 05:24:30 +0000760 # The only legal non-string value if we allow valueless
761 # options is None, so we need to check if the value is a
762 # string if:
763 # - we do not allow valueless options, or
764 # - we allow valueless options but the value is not None
765 if self._optcre is self.OPTCRE or value:
766 if not isinstance(value, basestring):
767 raise TypeError("option values must be strings")
Fred Drake0a1fa0e2010-08-10 13:09:54 +0000768 if value is not None:
769 # check for bad percent signs:
770 # first, replace all "good" interpolations
771 tmp_value = value.replace('%%', '')
772 tmp_value = self._interpvar_re.sub('', tmp_value)
773 # then, check if there's a lone percent sign left
774 if '%' in tmp_value:
775 raise ValueError("invalid interpolation syntax in %r at "
776 "position %d" % (value, tmp_value.find('%')))
David Goodger1cbf2062004-10-03 15:55:09 +0000777 ConfigParser.set(self, section, option, value)