| 1 | n/a | """Configuration file parser. |
|---|
| 2 | n/a | |
|---|
| 3 | n/a | A configuration file consists of sections, lead by a "[section]" header, |
|---|
| 4 | n/a | and followed by "name: value" entries, with continuations and such in |
|---|
| 5 | n/a | the style of RFC 822. |
|---|
| 6 | n/a | |
|---|
| 7 | n/a | Intrinsic defaults can be specified by passing them into the |
|---|
| 8 | n/a | ConfigParser constructor as a dictionary. |
|---|
| 9 | n/a | |
|---|
| 10 | n/a | class: |
|---|
| 11 | n/a | |
|---|
| 12 | n/a | ConfigParser -- responsible for parsing a list of |
|---|
| 13 | n/a | configuration files, and managing the parsed database. |
|---|
| 14 | n/a | |
|---|
| 15 | n/a | methods: |
|---|
| 16 | n/a | |
|---|
| 17 | n/a | __init__(defaults=None, dict_type=_default_dict, allow_no_value=False, |
|---|
| 18 | n/a | delimiters=('=', ':'), comment_prefixes=('#', ';'), |
|---|
| 19 | n/a | inline_comment_prefixes=None, strict=True, |
|---|
| 20 | n/a | empty_lines_in_values=True, default_section='DEFAULT', |
|---|
| 21 | n/a | interpolation=<unset>, converters=<unset>): |
|---|
| 22 | n/a | Create the parser. When `defaults' is given, it is initialized into the |
|---|
| 23 | n/a | dictionary or intrinsic defaults. The keys must be strings, the values |
|---|
| 24 | n/a | must be appropriate for %()s string interpolation. |
|---|
| 25 | n/a | |
|---|
| 26 | n/a | When `dict_type' is given, it will be used to create the dictionary |
|---|
| 27 | n/a | objects for the list of sections, for the options within a section, and |
|---|
| 28 | n/a | for the default values. |
|---|
| 29 | n/a | |
|---|
| 30 | n/a | When `delimiters' is given, it will be used as the set of substrings |
|---|
| 31 | n/a | that divide keys from values. |
|---|
| 32 | n/a | |
|---|
| 33 | n/a | When `comment_prefixes' is given, it will be used as the set of |
|---|
| 34 | n/a | substrings that prefix comments in empty lines. Comments can be |
|---|
| 35 | n/a | indented. |
|---|
| 36 | n/a | |
|---|
| 37 | n/a | When `inline_comment_prefixes' is given, it will be used as the set of |
|---|
| 38 | n/a | substrings that prefix comments in non-empty lines. |
|---|
| 39 | n/a | |
|---|
| 40 | n/a | When `strict` is True, the parser won't allow for any section or option |
|---|
| 41 | n/a | duplicates while reading from a single source (file, string or |
|---|
| 42 | n/a | dictionary). Default is True. |
|---|
| 43 | n/a | |
|---|
| 44 | n/a | When `empty_lines_in_values' is False (default: True), each empty line |
|---|
| 45 | n/a | marks the end of an option. Otherwise, internal empty lines of |
|---|
| 46 | n/a | a multiline option are kept as part of the value. |
|---|
| 47 | n/a | |
|---|
| 48 | n/a | When `allow_no_value' is True (default: False), options without |
|---|
| 49 | n/a | values are accepted; the value presented for these is None. |
|---|
| 50 | n/a | |
|---|
| 51 | n/a | When `default_section' is given, the name of the special section is |
|---|
| 52 | n/a | named accordingly. By default it is called ``"DEFAULT"`` but this can |
|---|
| 53 | n/a | be customized to point to any other valid section name. Its current |
|---|
| 54 | n/a | value can be retrieved using the ``parser_instance.default_section`` |
|---|
| 55 | n/a | attribute and may be modified at runtime. |
|---|
| 56 | n/a | |
|---|
| 57 | n/a | When `interpolation` is given, it should be an Interpolation subclass |
|---|
| 58 | n/a | instance. It will be used as the handler for option value |
|---|
| 59 | n/a | pre-processing when using getters. RawConfigParser object s don't do |
|---|
| 60 | n/a | any sort of interpolation, whereas ConfigParser uses an instance of |
|---|
| 61 | n/a | BasicInterpolation. The library also provides a ``zc.buildbot`` |
|---|
| 62 | n/a | inspired ExtendedInterpolation implementation. |
|---|
| 63 | n/a | |
|---|
| 64 | n/a | When `converters` is given, it should be a dictionary where each key |
|---|
| 65 | n/a | represents the name of a type converter and each value is a callable |
|---|
| 66 | n/a | implementing the conversion from string to the desired datatype. Every |
|---|
| 67 | n/a | converter gets its corresponding get*() method on the parser object and |
|---|
| 68 | n/a | section proxies. |
|---|
| 69 | n/a | |
|---|
| 70 | n/a | sections() |
|---|
| 71 | n/a | Return all the configuration section names, sans DEFAULT. |
|---|
| 72 | n/a | |
|---|
| 73 | n/a | has_section(section) |
|---|
| 74 | n/a | Return whether the given section exists. |
|---|
| 75 | n/a | |
|---|
| 76 | n/a | has_option(section, option) |
|---|
| 77 | n/a | Return whether the given option exists in the given section. |
|---|
| 78 | n/a | |
|---|
| 79 | n/a | options(section) |
|---|
| 80 | n/a | Return list of configuration options for the named section. |
|---|
| 81 | n/a | |
|---|
| 82 | n/a | read(filenames, encoding=None) |
|---|
| 83 | n/a | Read and parse the list of named configuration files, given by |
|---|
| 84 | n/a | name. A single filename is also allowed. Non-existing files |
|---|
| 85 | n/a | are ignored. Return list of successfully read files. |
|---|
| 86 | n/a | |
|---|
| 87 | n/a | read_file(f, filename=None) |
|---|
| 88 | n/a | Read and parse one configuration file, given as a file object. |
|---|
| 89 | n/a | The filename defaults to f.name; it is only used in error |
|---|
| 90 | n/a | messages (if f has no `name' attribute, the string `<???>' is used). |
|---|
| 91 | n/a | |
|---|
| 92 | n/a | read_string(string) |
|---|
| 93 | n/a | Read configuration from a given string. |
|---|
| 94 | n/a | |
|---|
| 95 | n/a | read_dict(dictionary) |
|---|
| 96 | n/a | Read configuration from a dictionary. Keys are section names, |
|---|
| 97 | n/a | values are dictionaries with keys and values that should be present |
|---|
| 98 | n/a | in the section. If the used dictionary type preserves order, sections |
|---|
| 99 | n/a | and their keys will be added in order. Values are automatically |
|---|
| 100 | n/a | converted to strings. |
|---|
| 101 | n/a | |
|---|
| 102 | n/a | get(section, option, raw=False, vars=None, fallback=_UNSET) |
|---|
| 103 | n/a | Return a string value for the named option. All % interpolations are |
|---|
| 104 | n/a | expanded in the return values, based on the defaults passed into the |
|---|
| 105 | n/a | constructor and the DEFAULT section. Additional substitutions may be |
|---|
| 106 | n/a | provided using the `vars' argument, which must be a dictionary whose |
|---|
| 107 | n/a | contents override any pre-existing defaults. If `option' is a key in |
|---|
| 108 | n/a | `vars', the value from `vars' is used. |
|---|
| 109 | n/a | |
|---|
| 110 | n/a | getint(section, options, raw=False, vars=None, fallback=_UNSET) |
|---|
| 111 | n/a | Like get(), but convert value to an integer. |
|---|
| 112 | n/a | |
|---|
| 113 | n/a | getfloat(section, options, raw=False, vars=None, fallback=_UNSET) |
|---|
| 114 | n/a | Like get(), but convert value to a float. |
|---|
| 115 | n/a | |
|---|
| 116 | n/a | getboolean(section, options, raw=False, vars=None, fallback=_UNSET) |
|---|
| 117 | n/a | Like get(), but convert value to a boolean (currently case |
|---|
| 118 | n/a | insensitively defined as 0, false, no, off for False, and 1, true, |
|---|
| 119 | n/a | yes, on for True). Returns False or True. |
|---|
| 120 | n/a | |
|---|
| 121 | n/a | items(section=_UNSET, raw=False, vars=None) |
|---|
| 122 | n/a | If section is given, return a list of tuples with (name, value) for |
|---|
| 123 | n/a | each option in the section. Otherwise, return a list of tuples with |
|---|
| 124 | n/a | (section_name, section_proxy) for each section, including DEFAULTSECT. |
|---|
| 125 | n/a | |
|---|
| 126 | n/a | remove_section(section) |
|---|
| 127 | n/a | Remove the given file section and all its options. |
|---|
| 128 | n/a | |
|---|
| 129 | n/a | remove_option(section, option) |
|---|
| 130 | n/a | Remove the given option from the given section. |
|---|
| 131 | n/a | |
|---|
| 132 | n/a | set(section, option, value) |
|---|
| 133 | n/a | Set the given option. |
|---|
| 134 | n/a | |
|---|
| 135 | n/a | write(fp, space_around_delimiters=True) |
|---|
| 136 | n/a | Write the configuration state in .ini format. If |
|---|
| 137 | n/a | `space_around_delimiters' is True (the default), delimiters |
|---|
| 138 | n/a | between keys and values are surrounded by spaces. |
|---|
| 139 | n/a | """ |
|---|
| 140 | n/a | |
|---|
| 141 | n/a | from collections.abc import MutableMapping |
|---|
| 142 | n/a | from collections import OrderedDict as _default_dict, ChainMap as _ChainMap |
|---|
| 143 | n/a | import functools |
|---|
| 144 | n/a | import io |
|---|
| 145 | n/a | import itertools |
|---|
| 146 | n/a | import re |
|---|
| 147 | n/a | import sys |
|---|
| 148 | n/a | import warnings |
|---|
| 149 | n/a | |
|---|
| 150 | n/a | __all__ = ["NoSectionError", "DuplicateOptionError", "DuplicateSectionError", |
|---|
| 151 | n/a | "NoOptionError", "InterpolationError", "InterpolationDepthError", |
|---|
| 152 | n/a | "InterpolationMissingOptionError", "InterpolationSyntaxError", |
|---|
| 153 | n/a | "ParsingError", "MissingSectionHeaderError", |
|---|
| 154 | n/a | "ConfigParser", "SafeConfigParser", "RawConfigParser", |
|---|
| 155 | n/a | "Interpolation", "BasicInterpolation", "ExtendedInterpolation", |
|---|
| 156 | n/a | "LegacyInterpolation", "SectionProxy", "ConverterMapping", |
|---|
| 157 | n/a | "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"] |
|---|
| 158 | n/a | |
|---|
| 159 | n/a | DEFAULTSECT = "DEFAULT" |
|---|
| 160 | n/a | |
|---|
| 161 | n/a | MAX_INTERPOLATION_DEPTH = 10 |
|---|
| 162 | n/a | |
|---|
| 163 | n/a | |
|---|
| 164 | n/a | |
|---|
| 165 | n/a | # exception classes |
|---|
| 166 | n/a | class Error(Exception): |
|---|
| 167 | n/a | """Base class for ConfigParser exceptions.""" |
|---|
| 168 | n/a | |
|---|
| 169 | n/a | def __init__(self, msg=''): |
|---|
| 170 | n/a | self.message = msg |
|---|
| 171 | n/a | Exception.__init__(self, msg) |
|---|
| 172 | n/a | |
|---|
| 173 | n/a | def __repr__(self): |
|---|
| 174 | n/a | return self.message |
|---|
| 175 | n/a | |
|---|
| 176 | n/a | __str__ = __repr__ |
|---|
| 177 | n/a | |
|---|
| 178 | n/a | |
|---|
| 179 | n/a | class NoSectionError(Error): |
|---|
| 180 | n/a | """Raised when no section matches a requested option.""" |
|---|
| 181 | n/a | |
|---|
| 182 | n/a | def __init__(self, section): |
|---|
| 183 | n/a | Error.__init__(self, 'No section: %r' % (section,)) |
|---|
| 184 | n/a | self.section = section |
|---|
| 185 | n/a | self.args = (section, ) |
|---|
| 186 | n/a | |
|---|
| 187 | n/a | |
|---|
| 188 | n/a | class DuplicateSectionError(Error): |
|---|
| 189 | n/a | """Raised when a section is repeated in an input source. |
|---|
| 190 | n/a | |
|---|
| 191 | n/a | Possible repetitions that raise this exception are: multiple creation |
|---|
| 192 | n/a | using the API or in strict parsers when a section is found more than once |
|---|
| 193 | n/a | in a single input file, string or dictionary. |
|---|
| 194 | n/a | """ |
|---|
| 195 | n/a | |
|---|
| 196 | n/a | def __init__(self, section, source=None, lineno=None): |
|---|
| 197 | n/a | msg = [repr(section), " already exists"] |
|---|
| 198 | n/a | if source is not None: |
|---|
| 199 | n/a | message = ["While reading from ", repr(source)] |
|---|
| 200 | n/a | if lineno is not None: |
|---|
| 201 | n/a | message.append(" [line {0:2d}]".format(lineno)) |
|---|
| 202 | n/a | message.append(": section ") |
|---|
| 203 | n/a | message.extend(msg) |
|---|
| 204 | n/a | msg = message |
|---|
| 205 | n/a | else: |
|---|
| 206 | n/a | msg.insert(0, "Section ") |
|---|
| 207 | n/a | Error.__init__(self, "".join(msg)) |
|---|
| 208 | n/a | self.section = section |
|---|
| 209 | n/a | self.source = source |
|---|
| 210 | n/a | self.lineno = lineno |
|---|
| 211 | n/a | self.args = (section, source, lineno) |
|---|
| 212 | n/a | |
|---|
| 213 | n/a | |
|---|
| 214 | n/a | class DuplicateOptionError(Error): |
|---|
| 215 | n/a | """Raised by strict parsers when an option is repeated in an input source. |
|---|
| 216 | n/a | |
|---|
| 217 | n/a | Current implementation raises this exception only when an option is found |
|---|
| 218 | n/a | more than once in a single file, string or dictionary. |
|---|
| 219 | n/a | """ |
|---|
| 220 | n/a | |
|---|
| 221 | n/a | def __init__(self, section, option, source=None, lineno=None): |
|---|
| 222 | n/a | msg = [repr(option), " in section ", repr(section), |
|---|
| 223 | n/a | " already exists"] |
|---|
| 224 | n/a | if source is not None: |
|---|
| 225 | n/a | message = ["While reading from ", repr(source)] |
|---|
| 226 | n/a | if lineno is not None: |
|---|
| 227 | n/a | message.append(" [line {0:2d}]".format(lineno)) |
|---|
| 228 | n/a | message.append(": option ") |
|---|
| 229 | n/a | message.extend(msg) |
|---|
| 230 | n/a | msg = message |
|---|
| 231 | n/a | else: |
|---|
| 232 | n/a | msg.insert(0, "Option ") |
|---|
| 233 | n/a | Error.__init__(self, "".join(msg)) |
|---|
| 234 | n/a | self.section = section |
|---|
| 235 | n/a | self.option = option |
|---|
| 236 | n/a | self.source = source |
|---|
| 237 | n/a | self.lineno = lineno |
|---|
| 238 | n/a | self.args = (section, option, source, lineno) |
|---|
| 239 | n/a | |
|---|
| 240 | n/a | |
|---|
| 241 | n/a | class NoOptionError(Error): |
|---|
| 242 | n/a | """A requested option was not found.""" |
|---|
| 243 | n/a | |
|---|
| 244 | n/a | def __init__(self, option, section): |
|---|
| 245 | n/a | Error.__init__(self, "No option %r in section: %r" % |
|---|
| 246 | n/a | (option, section)) |
|---|
| 247 | n/a | self.option = option |
|---|
| 248 | n/a | self.section = section |
|---|
| 249 | n/a | self.args = (option, section) |
|---|
| 250 | n/a | |
|---|
| 251 | n/a | |
|---|
| 252 | n/a | class InterpolationError(Error): |
|---|
| 253 | n/a | """Base class for interpolation-related exceptions.""" |
|---|
| 254 | n/a | |
|---|
| 255 | n/a | def __init__(self, option, section, msg): |
|---|
| 256 | n/a | Error.__init__(self, msg) |
|---|
| 257 | n/a | self.option = option |
|---|
| 258 | n/a | self.section = section |
|---|
| 259 | n/a | self.args = (option, section, msg) |
|---|
| 260 | n/a | |
|---|
| 261 | n/a | |
|---|
| 262 | n/a | class InterpolationMissingOptionError(InterpolationError): |
|---|
| 263 | n/a | """A string substitution required a setting which was not available.""" |
|---|
| 264 | n/a | |
|---|
| 265 | n/a | def __init__(self, option, section, rawval, reference): |
|---|
| 266 | n/a | msg = ("Bad value substitution: option {!r} in section {!r} contains " |
|---|
| 267 | n/a | "an interpolation key {!r} which is not a valid option name. " |
|---|
| 268 | n/a | "Raw value: {!r}".format(option, section, reference, rawval)) |
|---|
| 269 | n/a | InterpolationError.__init__(self, option, section, msg) |
|---|
| 270 | n/a | self.reference = reference |
|---|
| 271 | n/a | self.args = (option, section, rawval, reference) |
|---|
| 272 | n/a | |
|---|
| 273 | n/a | |
|---|
| 274 | n/a | class InterpolationSyntaxError(InterpolationError): |
|---|
| 275 | n/a | """Raised when the source text contains invalid syntax. |
|---|
| 276 | n/a | |
|---|
| 277 | n/a | Current implementation raises this exception when the source text into |
|---|
| 278 | n/a | which substitutions are made does not conform to the required syntax. |
|---|
| 279 | n/a | """ |
|---|
| 280 | n/a | |
|---|
| 281 | n/a | |
|---|
| 282 | n/a | class InterpolationDepthError(InterpolationError): |
|---|
| 283 | n/a | """Raised when substitutions are nested too deeply.""" |
|---|
| 284 | n/a | |
|---|
| 285 | n/a | def __init__(self, option, section, rawval): |
|---|
| 286 | n/a | msg = ("Recursion limit exceeded in value substitution: option {!r} " |
|---|
| 287 | n/a | "in section {!r} contains an interpolation key which " |
|---|
| 288 | n/a | "cannot be substituted in {} steps. Raw value: {!r}" |
|---|
| 289 | n/a | "".format(option, section, MAX_INTERPOLATION_DEPTH, |
|---|
| 290 | n/a | rawval)) |
|---|
| 291 | n/a | InterpolationError.__init__(self, option, section, msg) |
|---|
| 292 | n/a | self.args = (option, section, rawval) |
|---|
| 293 | n/a | |
|---|
| 294 | n/a | |
|---|
| 295 | n/a | class ParsingError(Error): |
|---|
| 296 | n/a | """Raised when a configuration file does not follow legal syntax.""" |
|---|
| 297 | n/a | |
|---|
| 298 | n/a | def __init__(self, source=None, filename=None): |
|---|
| 299 | n/a | # Exactly one of `source'/`filename' arguments has to be given. |
|---|
| 300 | n/a | # `filename' kept for compatibility. |
|---|
| 301 | n/a | if filename and source: |
|---|
| 302 | n/a | raise ValueError("Cannot specify both `filename' and `source'. " |
|---|
| 303 | n/a | "Use `source'.") |
|---|
| 304 | n/a | elif not filename and not source: |
|---|
| 305 | n/a | raise ValueError("Required argument `source' not given.") |
|---|
| 306 | n/a | elif filename: |
|---|
| 307 | n/a | source = filename |
|---|
| 308 | n/a | Error.__init__(self, 'Source contains parsing errors: %r' % source) |
|---|
| 309 | n/a | self.source = source |
|---|
| 310 | n/a | self.errors = [] |
|---|
| 311 | n/a | self.args = (source, ) |
|---|
| 312 | n/a | |
|---|
| 313 | n/a | @property |
|---|
| 314 | n/a | def filename(self): |
|---|
| 315 | n/a | """Deprecated, use `source'.""" |
|---|
| 316 | n/a | warnings.warn( |
|---|
| 317 | n/a | "The 'filename' attribute will be removed in future versions. " |
|---|
| 318 | n/a | "Use 'source' instead.", |
|---|
| 319 | n/a | DeprecationWarning, stacklevel=2 |
|---|
| 320 | n/a | ) |
|---|
| 321 | n/a | return self.source |
|---|
| 322 | n/a | |
|---|
| 323 | n/a | @filename.setter |
|---|
| 324 | n/a | def filename(self, value): |
|---|
| 325 | n/a | """Deprecated, user `source'.""" |
|---|
| 326 | n/a | warnings.warn( |
|---|
| 327 | n/a | "The 'filename' attribute will be removed in future versions. " |
|---|
| 328 | n/a | "Use 'source' instead.", |
|---|
| 329 | n/a | DeprecationWarning, stacklevel=2 |
|---|
| 330 | n/a | ) |
|---|
| 331 | n/a | self.source = value |
|---|
| 332 | n/a | |
|---|
| 333 | n/a | def append(self, lineno, line): |
|---|
| 334 | n/a | self.errors.append((lineno, line)) |
|---|
| 335 | n/a | self.message += '\n\t[line %2d]: %s' % (lineno, line) |
|---|
| 336 | n/a | |
|---|
| 337 | n/a | |
|---|
| 338 | n/a | class MissingSectionHeaderError(ParsingError): |
|---|
| 339 | n/a | """Raised when a key-value pair is found before any section header.""" |
|---|
| 340 | n/a | |
|---|
| 341 | n/a | def __init__(self, filename, lineno, line): |
|---|
| 342 | n/a | Error.__init__( |
|---|
| 343 | n/a | self, |
|---|
| 344 | n/a | 'File contains no section headers.\nfile: %r, line: %d\n%r' % |
|---|
| 345 | n/a | (filename, lineno, line)) |
|---|
| 346 | n/a | self.source = filename |
|---|
| 347 | n/a | self.lineno = lineno |
|---|
| 348 | n/a | self.line = line |
|---|
| 349 | n/a | self.args = (filename, lineno, line) |
|---|
| 350 | n/a | |
|---|
| 351 | n/a | |
|---|
| 352 | n/a | # Used in parser getters to indicate the default behaviour when a specific |
|---|
| 353 | n/a | # option is not found it to raise an exception. Created to enable `None' as |
|---|
| 354 | n/a | # a valid fallback value. |
|---|
| 355 | n/a | _UNSET = object() |
|---|
| 356 | n/a | |
|---|
| 357 | n/a | |
|---|
| 358 | n/a | class Interpolation: |
|---|
| 359 | n/a | """Dummy interpolation that passes the value through with no changes.""" |
|---|
| 360 | n/a | |
|---|
| 361 | n/a | def before_get(self, parser, section, option, value, defaults): |
|---|
| 362 | n/a | return value |
|---|
| 363 | n/a | |
|---|
| 364 | n/a | def before_set(self, parser, section, option, value): |
|---|
| 365 | n/a | return value |
|---|
| 366 | n/a | |
|---|
| 367 | n/a | def before_read(self, parser, section, option, value): |
|---|
| 368 | n/a | return value |
|---|
| 369 | n/a | |
|---|
| 370 | n/a | def before_write(self, parser, section, option, value): |
|---|
| 371 | n/a | return value |
|---|
| 372 | n/a | |
|---|
| 373 | n/a | |
|---|
| 374 | n/a | class BasicInterpolation(Interpolation): |
|---|
| 375 | n/a | """Interpolation as implemented in the classic ConfigParser. |
|---|
| 376 | n/a | |
|---|
| 377 | n/a | The option values can contain format strings which refer to other values in |
|---|
| 378 | n/a | the same section, or values in the special default section. |
|---|
| 379 | n/a | |
|---|
| 380 | n/a | For example: |
|---|
| 381 | n/a | |
|---|
| 382 | n/a | something: %(dir)s/whatever |
|---|
| 383 | n/a | |
|---|
| 384 | n/a | would resolve the "%(dir)s" to the value of dir. All reference |
|---|
| 385 | n/a | expansions are done late, on demand. If a user needs to use a bare % in |
|---|
| 386 | n/a | a configuration file, she can escape it by writing %%. Other % usage |
|---|
| 387 | n/a | is considered a user error and raises `InterpolationSyntaxError'.""" |
|---|
| 388 | n/a | |
|---|
| 389 | n/a | _KEYCRE = re.compile(r"%\(([^)]+)\)s") |
|---|
| 390 | n/a | |
|---|
| 391 | n/a | def before_get(self, parser, section, option, value, defaults): |
|---|
| 392 | n/a | L = [] |
|---|
| 393 | n/a | self._interpolate_some(parser, option, L, value, section, defaults, 1) |
|---|
| 394 | n/a | return ''.join(L) |
|---|
| 395 | n/a | |
|---|
| 396 | n/a | def before_set(self, parser, section, option, value): |
|---|
| 397 | n/a | tmp_value = value.replace('%%', '') # escaped percent signs |
|---|
| 398 | n/a | tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax |
|---|
| 399 | n/a | if '%' in tmp_value: |
|---|
| 400 | n/a | raise ValueError("invalid interpolation syntax in %r at " |
|---|
| 401 | n/a | "position %d" % (value, tmp_value.find('%'))) |
|---|
| 402 | n/a | return value |
|---|
| 403 | n/a | |
|---|
| 404 | n/a | def _interpolate_some(self, parser, option, accum, rest, section, map, |
|---|
| 405 | n/a | depth): |
|---|
| 406 | n/a | rawval = parser.get(section, option, raw=True, fallback=rest) |
|---|
| 407 | n/a | if depth > MAX_INTERPOLATION_DEPTH: |
|---|
| 408 | n/a | raise InterpolationDepthError(option, section, rawval) |
|---|
| 409 | n/a | while rest: |
|---|
| 410 | n/a | p = rest.find("%") |
|---|
| 411 | n/a | if p < 0: |
|---|
| 412 | n/a | accum.append(rest) |
|---|
| 413 | n/a | return |
|---|
| 414 | n/a | if p > 0: |
|---|
| 415 | n/a | accum.append(rest[:p]) |
|---|
| 416 | n/a | rest = rest[p:] |
|---|
| 417 | n/a | # p is no longer used |
|---|
| 418 | n/a | c = rest[1:2] |
|---|
| 419 | n/a | if c == "%": |
|---|
| 420 | n/a | accum.append("%") |
|---|
| 421 | n/a | rest = rest[2:] |
|---|
| 422 | n/a | elif c == "(": |
|---|
| 423 | n/a | m = self._KEYCRE.match(rest) |
|---|
| 424 | n/a | if m is None: |
|---|
| 425 | n/a | raise InterpolationSyntaxError(option, section, |
|---|
| 426 | n/a | "bad interpolation variable reference %r" % rest) |
|---|
| 427 | n/a | var = parser.optionxform(m.group(1)) |
|---|
| 428 | n/a | rest = rest[m.end():] |
|---|
| 429 | n/a | try: |
|---|
| 430 | n/a | v = map[var] |
|---|
| 431 | n/a | except KeyError: |
|---|
| 432 | n/a | raise InterpolationMissingOptionError( |
|---|
| 433 | n/a | option, section, rawval, var) from None |
|---|
| 434 | n/a | if "%" in v: |
|---|
| 435 | n/a | self._interpolate_some(parser, option, accum, v, |
|---|
| 436 | n/a | section, map, depth + 1) |
|---|
| 437 | n/a | else: |
|---|
| 438 | n/a | accum.append(v) |
|---|
| 439 | n/a | else: |
|---|
| 440 | n/a | raise InterpolationSyntaxError( |
|---|
| 441 | n/a | option, section, |
|---|
| 442 | n/a | "'%%' must be followed by '%%' or '(', " |
|---|
| 443 | n/a | "found: %r" % (rest,)) |
|---|
| 444 | n/a | |
|---|
| 445 | n/a | |
|---|
| 446 | n/a | class ExtendedInterpolation(Interpolation): |
|---|
| 447 | n/a | """Advanced variant of interpolation, supports the syntax used by |
|---|
| 448 | n/a | `zc.buildout'. Enables interpolation between sections.""" |
|---|
| 449 | n/a | |
|---|
| 450 | n/a | _KEYCRE = re.compile(r"\$\{([^}]+)\}") |
|---|
| 451 | n/a | |
|---|
| 452 | n/a | def before_get(self, parser, section, option, value, defaults): |
|---|
| 453 | n/a | L = [] |
|---|
| 454 | n/a | self._interpolate_some(parser, option, L, value, section, defaults, 1) |
|---|
| 455 | n/a | return ''.join(L) |
|---|
| 456 | n/a | |
|---|
| 457 | n/a | def before_set(self, parser, section, option, value): |
|---|
| 458 | n/a | tmp_value = value.replace('$$', '') # escaped dollar signs |
|---|
| 459 | n/a | tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax |
|---|
| 460 | n/a | if '$' in tmp_value: |
|---|
| 461 | n/a | raise ValueError("invalid interpolation syntax in %r at " |
|---|
| 462 | n/a | "position %d" % (value, tmp_value.find('$'))) |
|---|
| 463 | n/a | return value |
|---|
| 464 | n/a | |
|---|
| 465 | n/a | def _interpolate_some(self, parser, option, accum, rest, section, map, |
|---|
| 466 | n/a | depth): |
|---|
| 467 | n/a | rawval = parser.get(section, option, raw=True, fallback=rest) |
|---|
| 468 | n/a | if depth > MAX_INTERPOLATION_DEPTH: |
|---|
| 469 | n/a | raise InterpolationDepthError(option, section, rawval) |
|---|
| 470 | n/a | while rest: |
|---|
| 471 | n/a | p = rest.find("$") |
|---|
| 472 | n/a | if p < 0: |
|---|
| 473 | n/a | accum.append(rest) |
|---|
| 474 | n/a | return |
|---|
| 475 | n/a | if p > 0: |
|---|
| 476 | n/a | accum.append(rest[:p]) |
|---|
| 477 | n/a | rest = rest[p:] |
|---|
| 478 | n/a | # p is no longer used |
|---|
| 479 | n/a | c = rest[1:2] |
|---|
| 480 | n/a | if c == "$": |
|---|
| 481 | n/a | accum.append("$") |
|---|
| 482 | n/a | rest = rest[2:] |
|---|
| 483 | n/a | elif c == "{": |
|---|
| 484 | n/a | m = self._KEYCRE.match(rest) |
|---|
| 485 | n/a | if m is None: |
|---|
| 486 | n/a | raise InterpolationSyntaxError(option, section, |
|---|
| 487 | n/a | "bad interpolation variable reference %r" % rest) |
|---|
| 488 | n/a | path = m.group(1).split(':') |
|---|
| 489 | n/a | rest = rest[m.end():] |
|---|
| 490 | n/a | sect = section |
|---|
| 491 | n/a | opt = option |
|---|
| 492 | n/a | try: |
|---|
| 493 | n/a | if len(path) == 1: |
|---|
| 494 | n/a | opt = parser.optionxform(path[0]) |
|---|
| 495 | n/a | v = map[opt] |
|---|
| 496 | n/a | elif len(path) == 2: |
|---|
| 497 | n/a | sect = path[0] |
|---|
| 498 | n/a | opt = parser.optionxform(path[1]) |
|---|
| 499 | n/a | v = parser.get(sect, opt, raw=True) |
|---|
| 500 | n/a | else: |
|---|
| 501 | n/a | raise InterpolationSyntaxError( |
|---|
| 502 | n/a | option, section, |
|---|
| 503 | n/a | "More than one ':' found: %r" % (rest,)) |
|---|
| 504 | n/a | except (KeyError, NoSectionError, NoOptionError): |
|---|
| 505 | n/a | raise InterpolationMissingOptionError( |
|---|
| 506 | n/a | option, section, rawval, ":".join(path)) from None |
|---|
| 507 | n/a | if "$" in v: |
|---|
| 508 | n/a | self._interpolate_some(parser, opt, accum, v, sect, |
|---|
| 509 | n/a | dict(parser.items(sect, raw=True)), |
|---|
| 510 | n/a | depth + 1) |
|---|
| 511 | n/a | else: |
|---|
| 512 | n/a | accum.append(v) |
|---|
| 513 | n/a | else: |
|---|
| 514 | n/a | raise InterpolationSyntaxError( |
|---|
| 515 | n/a | option, section, |
|---|
| 516 | n/a | "'$' must be followed by '$' or '{', " |
|---|
| 517 | n/a | "found: %r" % (rest,)) |
|---|
| 518 | n/a | |
|---|
| 519 | n/a | |
|---|
| 520 | n/a | class LegacyInterpolation(Interpolation): |
|---|
| 521 | n/a | """Deprecated interpolation used in old versions of ConfigParser. |
|---|
| 522 | n/a | Use BasicInterpolation or ExtendedInterpolation instead.""" |
|---|
| 523 | n/a | |
|---|
| 524 | n/a | _KEYCRE = re.compile(r"%\(([^)]*)\)s|.") |
|---|
| 525 | n/a | |
|---|
| 526 | n/a | def before_get(self, parser, section, option, value, vars): |
|---|
| 527 | n/a | rawval = value |
|---|
| 528 | n/a | depth = MAX_INTERPOLATION_DEPTH |
|---|
| 529 | n/a | while depth: # Loop through this until it's done |
|---|
| 530 | n/a | depth -= 1 |
|---|
| 531 | n/a | if value and "%(" in value: |
|---|
| 532 | n/a | replace = functools.partial(self._interpolation_replace, |
|---|
| 533 | n/a | parser=parser) |
|---|
| 534 | n/a | value = self._KEYCRE.sub(replace, value) |
|---|
| 535 | n/a | try: |
|---|
| 536 | n/a | value = value % vars |
|---|
| 537 | n/a | except KeyError as e: |
|---|
| 538 | n/a | raise InterpolationMissingOptionError( |
|---|
| 539 | n/a | option, section, rawval, e.args[0]) from None |
|---|
| 540 | n/a | else: |
|---|
| 541 | n/a | break |
|---|
| 542 | n/a | if value and "%(" in value: |
|---|
| 543 | n/a | raise InterpolationDepthError(option, section, rawval) |
|---|
| 544 | n/a | return value |
|---|
| 545 | n/a | |
|---|
| 546 | n/a | def before_set(self, parser, section, option, value): |
|---|
| 547 | n/a | return value |
|---|
| 548 | n/a | |
|---|
| 549 | n/a | @staticmethod |
|---|
| 550 | n/a | def _interpolation_replace(match, parser): |
|---|
| 551 | n/a | s = match.group(1) |
|---|
| 552 | n/a | if s is None: |
|---|
| 553 | n/a | return match.group() |
|---|
| 554 | n/a | else: |
|---|
| 555 | n/a | return "%%(%s)s" % parser.optionxform(s) |
|---|
| 556 | n/a | |
|---|
| 557 | n/a | |
|---|
| 558 | n/a | class RawConfigParser(MutableMapping): |
|---|
| 559 | n/a | """ConfigParser that does not do interpolation.""" |
|---|
| 560 | n/a | |
|---|
| 561 | n/a | # Regular expressions for parsing section headers and options |
|---|
| 562 | n/a | _SECT_TMPL = r""" |
|---|
| 563 | n/a | \[ # [ |
|---|
| 564 | n/a | (?P<header>[^]]+) # very permissive! |
|---|
| 565 | n/a | \] # ] |
|---|
| 566 | n/a | """ |
|---|
| 567 | n/a | _OPT_TMPL = r""" |
|---|
| 568 | n/a | (?P<option>.*?) # very permissive! |
|---|
| 569 | n/a | \s*(?P<vi>{delim})\s* # any number of space/tab, |
|---|
| 570 | n/a | # followed by any of the |
|---|
| 571 | n/a | # allowed delimiters, |
|---|
| 572 | n/a | # followed by any space/tab |
|---|
| 573 | n/a | (?P<value>.*)$ # everything up to eol |
|---|
| 574 | n/a | """ |
|---|
| 575 | n/a | _OPT_NV_TMPL = r""" |
|---|
| 576 | n/a | (?P<option>.*?) # very permissive! |
|---|
| 577 | n/a | \s*(?: # any number of space/tab, |
|---|
| 578 | n/a | (?P<vi>{delim})\s* # optionally followed by |
|---|
| 579 | n/a | # any of the allowed |
|---|
| 580 | n/a | # delimiters, followed by any |
|---|
| 581 | n/a | # space/tab |
|---|
| 582 | n/a | (?P<value>.*))?$ # everything up to eol |
|---|
| 583 | n/a | """ |
|---|
| 584 | n/a | # Interpolation algorithm to be used if the user does not specify another |
|---|
| 585 | n/a | _DEFAULT_INTERPOLATION = Interpolation() |
|---|
| 586 | n/a | # Compiled regular expression for matching sections |
|---|
| 587 | n/a | SECTCRE = re.compile(_SECT_TMPL, re.VERBOSE) |
|---|
| 588 | n/a | # Compiled regular expression for matching options with typical separators |
|---|
| 589 | n/a | OPTCRE = re.compile(_OPT_TMPL.format(delim="=|:"), re.VERBOSE) |
|---|
| 590 | n/a | # Compiled regular expression for matching options with optional values |
|---|
| 591 | n/a | # delimited using typical separators |
|---|
| 592 | n/a | OPTCRE_NV = re.compile(_OPT_NV_TMPL.format(delim="=|:"), re.VERBOSE) |
|---|
| 593 | n/a | # Compiled regular expression for matching leading whitespace in a line |
|---|
| 594 | n/a | NONSPACECRE = re.compile(r"\S") |
|---|
| 595 | n/a | # Possible boolean values in the configuration. |
|---|
| 596 | n/a | BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True, |
|---|
| 597 | n/a | '0': False, 'no': False, 'false': False, 'off': False} |
|---|
| 598 | n/a | |
|---|
| 599 | n/a | def __init__(self, defaults=None, dict_type=_default_dict, |
|---|
| 600 | n/a | allow_no_value=False, *, delimiters=('=', ':'), |
|---|
| 601 | n/a | comment_prefixes=('#', ';'), inline_comment_prefixes=None, |
|---|
| 602 | n/a | strict=True, empty_lines_in_values=True, |
|---|
| 603 | n/a | default_section=DEFAULTSECT, |
|---|
| 604 | n/a | interpolation=_UNSET, converters=_UNSET): |
|---|
| 605 | n/a | |
|---|
| 606 | n/a | self._dict = dict_type |
|---|
| 607 | n/a | self._sections = self._dict() |
|---|
| 608 | n/a | self._defaults = self._dict() |
|---|
| 609 | n/a | self._converters = ConverterMapping(self) |
|---|
| 610 | n/a | self._proxies = self._dict() |
|---|
| 611 | n/a | self._proxies[default_section] = SectionProxy(self, default_section) |
|---|
| 612 | n/a | if defaults: |
|---|
| 613 | n/a | for key, value in defaults.items(): |
|---|
| 614 | n/a | self._defaults[self.optionxform(key)] = value |
|---|
| 615 | n/a | self._delimiters = tuple(delimiters) |
|---|
| 616 | n/a | if delimiters == ('=', ':'): |
|---|
| 617 | n/a | self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE |
|---|
| 618 | n/a | else: |
|---|
| 619 | n/a | d = "|".join(re.escape(d) for d in delimiters) |
|---|
| 620 | n/a | if allow_no_value: |
|---|
| 621 | n/a | self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d), |
|---|
| 622 | n/a | re.VERBOSE) |
|---|
| 623 | n/a | else: |
|---|
| 624 | n/a | self._optcre = re.compile(self._OPT_TMPL.format(delim=d), |
|---|
| 625 | n/a | re.VERBOSE) |
|---|
| 626 | n/a | self._comment_prefixes = tuple(comment_prefixes or ()) |
|---|
| 627 | n/a | self._inline_comment_prefixes = tuple(inline_comment_prefixes or ()) |
|---|
| 628 | n/a | self._strict = strict |
|---|
| 629 | n/a | self._allow_no_value = allow_no_value |
|---|
| 630 | n/a | self._empty_lines_in_values = empty_lines_in_values |
|---|
| 631 | n/a | self.default_section=default_section |
|---|
| 632 | n/a | self._interpolation = interpolation |
|---|
| 633 | n/a | if self._interpolation is _UNSET: |
|---|
| 634 | n/a | self._interpolation = self._DEFAULT_INTERPOLATION |
|---|
| 635 | n/a | if self._interpolation is None: |
|---|
| 636 | n/a | self._interpolation = Interpolation() |
|---|
| 637 | n/a | if converters is not _UNSET: |
|---|
| 638 | n/a | self._converters.update(converters) |
|---|
| 639 | n/a | |
|---|
| 640 | n/a | def defaults(self): |
|---|
| 641 | n/a | return self._defaults |
|---|
| 642 | n/a | |
|---|
| 643 | n/a | def sections(self): |
|---|
| 644 | n/a | """Return a list of section names, excluding [DEFAULT]""" |
|---|
| 645 | n/a | # self._sections will never have [DEFAULT] in it |
|---|
| 646 | n/a | return list(self._sections.keys()) |
|---|
| 647 | n/a | |
|---|
| 648 | n/a | def add_section(self, section): |
|---|
| 649 | n/a | """Create a new section in the configuration. |
|---|
| 650 | n/a | |
|---|
| 651 | n/a | Raise DuplicateSectionError if a section by the specified name |
|---|
| 652 | n/a | already exists. Raise ValueError if name is DEFAULT. |
|---|
| 653 | n/a | """ |
|---|
| 654 | n/a | if section == self.default_section: |
|---|
| 655 | n/a | raise ValueError('Invalid section name: %r' % section) |
|---|
| 656 | n/a | |
|---|
| 657 | n/a | if section in self._sections: |
|---|
| 658 | n/a | raise DuplicateSectionError(section) |
|---|
| 659 | n/a | self._sections[section] = self._dict() |
|---|
| 660 | n/a | self._proxies[section] = SectionProxy(self, section) |
|---|
| 661 | n/a | |
|---|
| 662 | n/a | def has_section(self, section): |
|---|
| 663 | n/a | """Indicate whether the named section is present in the configuration. |
|---|
| 664 | n/a | |
|---|
| 665 | n/a | The DEFAULT section is not acknowledged. |
|---|
| 666 | n/a | """ |
|---|
| 667 | n/a | return section in self._sections |
|---|
| 668 | n/a | |
|---|
| 669 | n/a | def options(self, section): |
|---|
| 670 | n/a | """Return a list of option names for the given section name.""" |
|---|
| 671 | n/a | try: |
|---|
| 672 | n/a | opts = self._sections[section].copy() |
|---|
| 673 | n/a | except KeyError: |
|---|
| 674 | n/a | raise NoSectionError(section) from None |
|---|
| 675 | n/a | opts.update(self._defaults) |
|---|
| 676 | n/a | return list(opts.keys()) |
|---|
| 677 | n/a | |
|---|
| 678 | n/a | def read(self, filenames, encoding=None): |
|---|
| 679 | n/a | """Read and parse a filename or a list of filenames. |
|---|
| 680 | n/a | |
|---|
| 681 | n/a | Files that cannot be opened are silently ignored; this is |
|---|
| 682 | n/a | designed so that you can specify a list of potential |
|---|
| 683 | n/a | configuration file locations (e.g. current directory, user's |
|---|
| 684 | n/a | home directory, systemwide directory), and all existing |
|---|
| 685 | n/a | configuration files in the list will be read. A single |
|---|
| 686 | n/a | filename may also be given. |
|---|
| 687 | n/a | |
|---|
| 688 | n/a | Return list of successfully read files. |
|---|
| 689 | n/a | """ |
|---|
| 690 | n/a | if isinstance(filenames, str): |
|---|
| 691 | n/a | filenames = [filenames] |
|---|
| 692 | n/a | read_ok = [] |
|---|
| 693 | n/a | for filename in filenames: |
|---|
| 694 | n/a | try: |
|---|
| 695 | n/a | with open(filename, encoding=encoding) as fp: |
|---|
| 696 | n/a | self._read(fp, filename) |
|---|
| 697 | n/a | except OSError: |
|---|
| 698 | n/a | continue |
|---|
| 699 | n/a | read_ok.append(filename) |
|---|
| 700 | n/a | return read_ok |
|---|
| 701 | n/a | |
|---|
| 702 | n/a | def read_file(self, f, source=None): |
|---|
| 703 | n/a | """Like read() but the argument must be a file-like object. |
|---|
| 704 | n/a | |
|---|
| 705 | n/a | The `f' argument must be iterable, returning one line at a time. |
|---|
| 706 | n/a | Optional second argument is the `source' specifying the name of the |
|---|
| 707 | n/a | file being read. If not given, it is taken from f.name. If `f' has no |
|---|
| 708 | n/a | `name' attribute, `<???>' is used. |
|---|
| 709 | n/a | """ |
|---|
| 710 | n/a | if source is None: |
|---|
| 711 | n/a | try: |
|---|
| 712 | n/a | source = f.name |
|---|
| 713 | n/a | except AttributeError: |
|---|
| 714 | n/a | source = '<???>' |
|---|
| 715 | n/a | self._read(f, source) |
|---|
| 716 | n/a | |
|---|
| 717 | n/a | def read_string(self, string, source='<string>'): |
|---|
| 718 | n/a | """Read configuration from a given string.""" |
|---|
| 719 | n/a | sfile = io.StringIO(string) |
|---|
| 720 | n/a | self.read_file(sfile, source) |
|---|
| 721 | n/a | |
|---|
| 722 | n/a | def read_dict(self, dictionary, source='<dict>'): |
|---|
| 723 | n/a | """Read configuration from a dictionary. |
|---|
| 724 | n/a | |
|---|
| 725 | n/a | Keys are section names, values are dictionaries with keys and values |
|---|
| 726 | n/a | that should be present in the section. If the used dictionary type |
|---|
| 727 | n/a | preserves order, sections and their keys will be added in order. |
|---|
| 728 | n/a | |
|---|
| 729 | n/a | All types held in the dictionary are converted to strings during |
|---|
| 730 | n/a | reading, including section names, option names and keys. |
|---|
| 731 | n/a | |
|---|
| 732 | n/a | Optional second argument is the `source' specifying the name of the |
|---|
| 733 | n/a | dictionary being read. |
|---|
| 734 | n/a | """ |
|---|
| 735 | n/a | elements_added = set() |
|---|
| 736 | n/a | for section, keys in dictionary.items(): |
|---|
| 737 | n/a | section = str(section) |
|---|
| 738 | n/a | try: |
|---|
| 739 | n/a | self.add_section(section) |
|---|
| 740 | n/a | except (DuplicateSectionError, ValueError): |
|---|
| 741 | n/a | if self._strict and section in elements_added: |
|---|
| 742 | n/a | raise |
|---|
| 743 | n/a | elements_added.add(section) |
|---|
| 744 | n/a | for key, value in keys.items(): |
|---|
| 745 | n/a | key = self.optionxform(str(key)) |
|---|
| 746 | n/a | if value is not None: |
|---|
| 747 | n/a | value = str(value) |
|---|
| 748 | n/a | if self._strict and (section, key) in elements_added: |
|---|
| 749 | n/a | raise DuplicateOptionError(section, key, source) |
|---|
| 750 | n/a | elements_added.add((section, key)) |
|---|
| 751 | n/a | self.set(section, key, value) |
|---|
| 752 | n/a | |
|---|
| 753 | n/a | def readfp(self, fp, filename=None): |
|---|
| 754 | n/a | """Deprecated, use read_file instead.""" |
|---|
| 755 | n/a | warnings.warn( |
|---|
| 756 | n/a | "This method will be removed in future versions. " |
|---|
| 757 | n/a | "Use 'parser.read_file()' instead.", |
|---|
| 758 | n/a | DeprecationWarning, stacklevel=2 |
|---|
| 759 | n/a | ) |
|---|
| 760 | n/a | self.read_file(fp, source=filename) |
|---|
| 761 | n/a | |
|---|
| 762 | n/a | def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET): |
|---|
| 763 | n/a | """Get an option value for a given section. |
|---|
| 764 | n/a | |
|---|
| 765 | n/a | If `vars' is provided, it must be a dictionary. The option is looked up |
|---|
| 766 | n/a | in `vars' (if provided), `section', and in `DEFAULTSECT' in that order. |
|---|
| 767 | n/a | If the key is not found and `fallback' is provided, it is used as |
|---|
| 768 | n/a | a fallback value. `None' can be provided as a `fallback' value. |
|---|
| 769 | n/a | |
|---|
| 770 | n/a | If interpolation is enabled and the optional argument `raw' is False, |
|---|
| 771 | n/a | all interpolations are expanded in the return values. |
|---|
| 772 | n/a | |
|---|
| 773 | n/a | Arguments `raw', `vars', and `fallback' are keyword only. |
|---|
| 774 | n/a | |
|---|
| 775 | n/a | The section DEFAULT is special. |
|---|
| 776 | n/a | """ |
|---|
| 777 | n/a | try: |
|---|
| 778 | n/a | d = self._unify_values(section, vars) |
|---|
| 779 | n/a | except NoSectionError: |
|---|
| 780 | n/a | if fallback is _UNSET: |
|---|
| 781 | n/a | raise |
|---|
| 782 | n/a | else: |
|---|
| 783 | n/a | return fallback |
|---|
| 784 | n/a | option = self.optionxform(option) |
|---|
| 785 | n/a | try: |
|---|
| 786 | n/a | value = d[option] |
|---|
| 787 | n/a | except KeyError: |
|---|
| 788 | n/a | if fallback is _UNSET: |
|---|
| 789 | n/a | raise NoOptionError(option, section) |
|---|
| 790 | n/a | else: |
|---|
| 791 | n/a | return fallback |
|---|
| 792 | n/a | |
|---|
| 793 | n/a | if raw or value is None: |
|---|
| 794 | n/a | return value |
|---|
| 795 | n/a | else: |
|---|
| 796 | n/a | return self._interpolation.before_get(self, section, option, value, |
|---|
| 797 | n/a | d) |
|---|
| 798 | n/a | |
|---|
| 799 | n/a | def _get(self, section, conv, option, **kwargs): |
|---|
| 800 | n/a | return conv(self.get(section, option, **kwargs)) |
|---|
| 801 | n/a | |
|---|
| 802 | n/a | def _get_conv(self, section, option, conv, *, raw=False, vars=None, |
|---|
| 803 | n/a | fallback=_UNSET, **kwargs): |
|---|
| 804 | n/a | try: |
|---|
| 805 | n/a | return self._get(section, conv, option, raw=raw, vars=vars, |
|---|
| 806 | n/a | **kwargs) |
|---|
| 807 | n/a | except (NoSectionError, NoOptionError): |
|---|
| 808 | n/a | if fallback is _UNSET: |
|---|
| 809 | n/a | raise |
|---|
| 810 | n/a | return fallback |
|---|
| 811 | n/a | |
|---|
| 812 | n/a | # getint, getfloat and getboolean provided directly for backwards compat |
|---|
| 813 | n/a | def getint(self, section, option, *, raw=False, vars=None, |
|---|
| 814 | n/a | fallback=_UNSET, **kwargs): |
|---|
| 815 | n/a | return self._get_conv(section, option, int, raw=raw, vars=vars, |
|---|
| 816 | n/a | fallback=fallback, **kwargs) |
|---|
| 817 | n/a | |
|---|
| 818 | n/a | def getfloat(self, section, option, *, raw=False, vars=None, |
|---|
| 819 | n/a | fallback=_UNSET, **kwargs): |
|---|
| 820 | n/a | return self._get_conv(section, option, float, raw=raw, vars=vars, |
|---|
| 821 | n/a | fallback=fallback, **kwargs) |
|---|
| 822 | n/a | |
|---|
| 823 | n/a | def getboolean(self, section, option, *, raw=False, vars=None, |
|---|
| 824 | n/a | fallback=_UNSET, **kwargs): |
|---|
| 825 | n/a | return self._get_conv(section, option, self._convert_to_boolean, |
|---|
| 826 | n/a | raw=raw, vars=vars, fallback=fallback, **kwargs) |
|---|
| 827 | n/a | |
|---|
| 828 | n/a | def items(self, section=_UNSET, raw=False, vars=None): |
|---|
| 829 | n/a | """Return a list of (name, value) tuples for each option in a section. |
|---|
| 830 | n/a | |
|---|
| 831 | n/a | All % interpolations are expanded in the return values, based on the |
|---|
| 832 | n/a | defaults passed into the constructor, unless the optional argument |
|---|
| 833 | n/a | `raw' is true. Additional substitutions may be provided using the |
|---|
| 834 | n/a | `vars' argument, which must be a dictionary whose contents overrides |
|---|
| 835 | n/a | any pre-existing defaults. |
|---|
| 836 | n/a | |
|---|
| 837 | n/a | The section DEFAULT is special. |
|---|
| 838 | n/a | """ |
|---|
| 839 | n/a | if section is _UNSET: |
|---|
| 840 | n/a | return super().items() |
|---|
| 841 | n/a | d = self._defaults.copy() |
|---|
| 842 | n/a | try: |
|---|
| 843 | n/a | d.update(self._sections[section]) |
|---|
| 844 | n/a | except KeyError: |
|---|
| 845 | n/a | if section != self.default_section: |
|---|
| 846 | n/a | raise NoSectionError(section) |
|---|
| 847 | n/a | # Update with the entry specific variables |
|---|
| 848 | n/a | if vars: |
|---|
| 849 | n/a | for key, value in vars.items(): |
|---|
| 850 | n/a | d[self.optionxform(key)] = value |
|---|
| 851 | n/a | value_getter = lambda option: self._interpolation.before_get(self, |
|---|
| 852 | n/a | section, option, d[option], d) |
|---|
| 853 | n/a | if raw: |
|---|
| 854 | n/a | value_getter = lambda option: d[option] |
|---|
| 855 | n/a | return [(option, value_getter(option)) for option in d.keys()] |
|---|
| 856 | n/a | |
|---|
| 857 | n/a | def popitem(self): |
|---|
| 858 | n/a | """Remove a section from the parser and return it as |
|---|
| 859 | n/a | a (section_name, section_proxy) tuple. If no section is present, raise |
|---|
| 860 | n/a | KeyError. |
|---|
| 861 | n/a | |
|---|
| 862 | n/a | The section DEFAULT is never returned because it cannot be removed. |
|---|
| 863 | n/a | """ |
|---|
| 864 | n/a | for key in self.sections(): |
|---|
| 865 | n/a | value = self[key] |
|---|
| 866 | n/a | del self[key] |
|---|
| 867 | n/a | return key, value |
|---|
| 868 | n/a | raise KeyError |
|---|
| 869 | n/a | |
|---|
| 870 | n/a | def optionxform(self, optionstr): |
|---|
| 871 | n/a | return optionstr.lower() |
|---|
| 872 | n/a | |
|---|
| 873 | n/a | def has_option(self, section, option): |
|---|
| 874 | n/a | """Check for the existence of a given option in a given section. |
|---|
| 875 | n/a | If the specified `section' is None or an empty string, DEFAULT is |
|---|
| 876 | n/a | assumed. If the specified `section' does not exist, returns False.""" |
|---|
| 877 | n/a | if not section or section == self.default_section: |
|---|
| 878 | n/a | option = self.optionxform(option) |
|---|
| 879 | n/a | return option in self._defaults |
|---|
| 880 | n/a | elif section not in self._sections: |
|---|
| 881 | n/a | return False |
|---|
| 882 | n/a | else: |
|---|
| 883 | n/a | option = self.optionxform(option) |
|---|
| 884 | n/a | return (option in self._sections[section] |
|---|
| 885 | n/a | or option in self._defaults) |
|---|
| 886 | n/a | |
|---|
| 887 | n/a | def set(self, section, option, value=None): |
|---|
| 888 | n/a | """Set an option.""" |
|---|
| 889 | n/a | if value: |
|---|
| 890 | n/a | value = self._interpolation.before_set(self, section, option, |
|---|
| 891 | n/a | value) |
|---|
| 892 | n/a | if not section or section == self.default_section: |
|---|
| 893 | n/a | sectdict = self._defaults |
|---|
| 894 | n/a | else: |
|---|
| 895 | n/a | try: |
|---|
| 896 | n/a | sectdict = self._sections[section] |
|---|
| 897 | n/a | except KeyError: |
|---|
| 898 | n/a | raise NoSectionError(section) from None |
|---|
| 899 | n/a | sectdict[self.optionxform(option)] = value |
|---|
| 900 | n/a | |
|---|
| 901 | n/a | def write(self, fp, space_around_delimiters=True): |
|---|
| 902 | n/a | """Write an .ini-format representation of the configuration state. |
|---|
| 903 | n/a | |
|---|
| 904 | n/a | If `space_around_delimiters' is True (the default), delimiters |
|---|
| 905 | n/a | between keys and values are surrounded by spaces. |
|---|
| 906 | n/a | """ |
|---|
| 907 | n/a | if space_around_delimiters: |
|---|
| 908 | n/a | d = " {} ".format(self._delimiters[0]) |
|---|
| 909 | n/a | else: |
|---|
| 910 | n/a | d = self._delimiters[0] |
|---|
| 911 | n/a | if self._defaults: |
|---|
| 912 | n/a | self._write_section(fp, self.default_section, |
|---|
| 913 | n/a | self._defaults.items(), d) |
|---|
| 914 | n/a | for section in self._sections: |
|---|
| 915 | n/a | self._write_section(fp, section, |
|---|
| 916 | n/a | self._sections[section].items(), d) |
|---|
| 917 | n/a | |
|---|
| 918 | n/a | def _write_section(self, fp, section_name, section_items, delimiter): |
|---|
| 919 | n/a | """Write a single section to the specified `fp'.""" |
|---|
| 920 | n/a | fp.write("[{}]\n".format(section_name)) |
|---|
| 921 | n/a | for key, value in section_items: |
|---|
| 922 | n/a | value = self._interpolation.before_write(self, section_name, key, |
|---|
| 923 | n/a | value) |
|---|
| 924 | n/a | if value is not None or not self._allow_no_value: |
|---|
| 925 | n/a | value = delimiter + str(value).replace('\n', '\n\t') |
|---|
| 926 | n/a | else: |
|---|
| 927 | n/a | value = "" |
|---|
| 928 | n/a | fp.write("{}{}\n".format(key, value)) |
|---|
| 929 | n/a | fp.write("\n") |
|---|
| 930 | n/a | |
|---|
| 931 | n/a | def remove_option(self, section, option): |
|---|
| 932 | n/a | """Remove an option.""" |
|---|
| 933 | n/a | if not section or section == self.default_section: |
|---|
| 934 | n/a | sectdict = self._defaults |
|---|
| 935 | n/a | else: |
|---|
| 936 | n/a | try: |
|---|
| 937 | n/a | sectdict = self._sections[section] |
|---|
| 938 | n/a | except KeyError: |
|---|
| 939 | n/a | raise NoSectionError(section) from None |
|---|
| 940 | n/a | option = self.optionxform(option) |
|---|
| 941 | n/a | existed = option in sectdict |
|---|
| 942 | n/a | if existed: |
|---|
| 943 | n/a | del sectdict[option] |
|---|
| 944 | n/a | return existed |
|---|
| 945 | n/a | |
|---|
| 946 | n/a | def remove_section(self, section): |
|---|
| 947 | n/a | """Remove a file section.""" |
|---|
| 948 | n/a | existed = section in self._sections |
|---|
| 949 | n/a | if existed: |
|---|
| 950 | n/a | del self._sections[section] |
|---|
| 951 | n/a | del self._proxies[section] |
|---|
| 952 | n/a | return existed |
|---|
| 953 | n/a | |
|---|
| 954 | n/a | def __getitem__(self, key): |
|---|
| 955 | n/a | if key != self.default_section and not self.has_section(key): |
|---|
| 956 | n/a | raise KeyError(key) |
|---|
| 957 | n/a | return self._proxies[key] |
|---|
| 958 | n/a | |
|---|
| 959 | n/a | def __setitem__(self, key, value): |
|---|
| 960 | n/a | # To conform with the mapping protocol, overwrites existing values in |
|---|
| 961 | n/a | # the section. |
|---|
| 962 | n/a | |
|---|
| 963 | n/a | # XXX this is not atomic if read_dict fails at any point. Then again, |
|---|
| 964 | n/a | # no update method in configparser is atomic in this implementation. |
|---|
| 965 | n/a | if key == self.default_section: |
|---|
| 966 | n/a | self._defaults.clear() |
|---|
| 967 | n/a | elif key in self._sections: |
|---|
| 968 | n/a | self._sections[key].clear() |
|---|
| 969 | n/a | self.read_dict({key: value}) |
|---|
| 970 | n/a | |
|---|
| 971 | n/a | def __delitem__(self, key): |
|---|
| 972 | n/a | if key == self.default_section: |
|---|
| 973 | n/a | raise ValueError("Cannot remove the default section.") |
|---|
| 974 | n/a | if not self.has_section(key): |
|---|
| 975 | n/a | raise KeyError(key) |
|---|
| 976 | n/a | self.remove_section(key) |
|---|
| 977 | n/a | |
|---|
| 978 | n/a | def __contains__(self, key): |
|---|
| 979 | n/a | return key == self.default_section or self.has_section(key) |
|---|
| 980 | n/a | |
|---|
| 981 | n/a | def __len__(self): |
|---|
| 982 | n/a | return len(self._sections) + 1 # the default section |
|---|
| 983 | n/a | |
|---|
| 984 | n/a | def __iter__(self): |
|---|
| 985 | n/a | # XXX does it break when underlying container state changed? |
|---|
| 986 | n/a | return itertools.chain((self.default_section,), self._sections.keys()) |
|---|
| 987 | n/a | |
|---|
| 988 | n/a | def _read(self, fp, fpname): |
|---|
| 989 | n/a | """Parse a sectioned configuration file. |
|---|
| 990 | n/a | |
|---|
| 991 | n/a | Each section in a configuration file contains a header, indicated by |
|---|
| 992 | n/a | a name in square brackets (`[]'), plus key/value options, indicated by |
|---|
| 993 | n/a | `name' and `value' delimited with a specific substring (`=' or `:' by |
|---|
| 994 | n/a | default). |
|---|
| 995 | n/a | |
|---|
| 996 | n/a | Values can span multiple lines, as long as they are indented deeper |
|---|
| 997 | n/a | than the first line of the value. Depending on the parser's mode, blank |
|---|
| 998 | n/a | lines may be treated as parts of multiline values or ignored. |
|---|
| 999 | n/a | |
|---|
| 1000 | n/a | Configuration files may include comments, prefixed by specific |
|---|
| 1001 | n/a | characters (`#' and `;' by default). Comments may appear on their own |
|---|
| 1002 | n/a | in an otherwise empty line or may be entered in lines holding values or |
|---|
| 1003 | n/a | section names. |
|---|
| 1004 | n/a | """ |
|---|
| 1005 | n/a | elements_added = set() |
|---|
| 1006 | n/a | cursect = None # None, or a dictionary |
|---|
| 1007 | n/a | sectname = None |
|---|
| 1008 | n/a | optname = None |
|---|
| 1009 | n/a | lineno = 0 |
|---|
| 1010 | n/a | indent_level = 0 |
|---|
| 1011 | n/a | e = None # None, or an exception |
|---|
| 1012 | n/a | for lineno, line in enumerate(fp, start=1): |
|---|
| 1013 | n/a | comment_start = sys.maxsize |
|---|
| 1014 | n/a | # strip inline comments |
|---|
| 1015 | n/a | inline_prefixes = {p: -1 for p in self._inline_comment_prefixes} |
|---|
| 1016 | n/a | while comment_start == sys.maxsize and inline_prefixes: |
|---|
| 1017 | n/a | next_prefixes = {} |
|---|
| 1018 | n/a | for prefix, index in inline_prefixes.items(): |
|---|
| 1019 | n/a | index = line.find(prefix, index+1) |
|---|
| 1020 | n/a | if index == -1: |
|---|
| 1021 | n/a | continue |
|---|
| 1022 | n/a | next_prefixes[prefix] = index |
|---|
| 1023 | n/a | if index == 0 or (index > 0 and line[index-1].isspace()): |
|---|
| 1024 | n/a | comment_start = min(comment_start, index) |
|---|
| 1025 | n/a | inline_prefixes = next_prefixes |
|---|
| 1026 | n/a | # strip full line comments |
|---|
| 1027 | n/a | for prefix in self._comment_prefixes: |
|---|
| 1028 | n/a | if line.strip().startswith(prefix): |
|---|
| 1029 | n/a | comment_start = 0 |
|---|
| 1030 | n/a | break |
|---|
| 1031 | n/a | if comment_start == sys.maxsize: |
|---|
| 1032 | n/a | comment_start = None |
|---|
| 1033 | n/a | value = line[:comment_start].strip() |
|---|
| 1034 | n/a | if not value: |
|---|
| 1035 | n/a | if self._empty_lines_in_values: |
|---|
| 1036 | n/a | # add empty line to the value, but only if there was no |
|---|
| 1037 | n/a | # comment on the line |
|---|
| 1038 | n/a | if (comment_start is None and |
|---|
| 1039 | n/a | cursect is not None and |
|---|
| 1040 | n/a | optname and |
|---|
| 1041 | n/a | cursect[optname] is not None): |
|---|
| 1042 | n/a | cursect[optname].append('') # newlines added at join |
|---|
| 1043 | n/a | else: |
|---|
| 1044 | n/a | # empty line marks end of value |
|---|
| 1045 | n/a | indent_level = sys.maxsize |
|---|
| 1046 | n/a | continue |
|---|
| 1047 | n/a | # continuation line? |
|---|
| 1048 | n/a | first_nonspace = self.NONSPACECRE.search(line) |
|---|
| 1049 | n/a | cur_indent_level = first_nonspace.start() if first_nonspace else 0 |
|---|
| 1050 | n/a | if (cursect is not None and optname and |
|---|
| 1051 | n/a | cur_indent_level > indent_level): |
|---|
| 1052 | n/a | cursect[optname].append(value) |
|---|
| 1053 | n/a | # a section header or option header? |
|---|
| 1054 | n/a | else: |
|---|
| 1055 | n/a | indent_level = cur_indent_level |
|---|
| 1056 | n/a | # is it a section header? |
|---|
| 1057 | n/a | mo = self.SECTCRE.match(value) |
|---|
| 1058 | n/a | if mo: |
|---|
| 1059 | n/a | sectname = mo.group('header') |
|---|
| 1060 | n/a | if sectname in self._sections: |
|---|
| 1061 | n/a | if self._strict and sectname in elements_added: |
|---|
| 1062 | n/a | raise DuplicateSectionError(sectname, fpname, |
|---|
| 1063 | n/a | lineno) |
|---|
| 1064 | n/a | cursect = self._sections[sectname] |
|---|
| 1065 | n/a | elements_added.add(sectname) |
|---|
| 1066 | n/a | elif sectname == self.default_section: |
|---|
| 1067 | n/a | cursect = self._defaults |
|---|
| 1068 | n/a | else: |
|---|
| 1069 | n/a | cursect = self._dict() |
|---|
| 1070 | n/a | self._sections[sectname] = cursect |
|---|
| 1071 | n/a | self._proxies[sectname] = SectionProxy(self, sectname) |
|---|
| 1072 | n/a | elements_added.add(sectname) |
|---|
| 1073 | n/a | # So sections can't start with a continuation line |
|---|
| 1074 | n/a | optname = None |
|---|
| 1075 | n/a | # no section header in the file? |
|---|
| 1076 | n/a | elif cursect is None: |
|---|
| 1077 | n/a | raise MissingSectionHeaderError(fpname, lineno, line) |
|---|
| 1078 | n/a | # an option line? |
|---|
| 1079 | n/a | else: |
|---|
| 1080 | n/a | mo = self._optcre.match(value) |
|---|
| 1081 | n/a | if mo: |
|---|
| 1082 | n/a | optname, vi, optval = mo.group('option', 'vi', 'value') |
|---|
| 1083 | n/a | if not optname: |
|---|
| 1084 | n/a | e = self._handle_error(e, fpname, lineno, line) |
|---|
| 1085 | n/a | optname = self.optionxform(optname.rstrip()) |
|---|
| 1086 | n/a | if (self._strict and |
|---|
| 1087 | n/a | (sectname, optname) in elements_added): |
|---|
| 1088 | n/a | raise DuplicateOptionError(sectname, optname, |
|---|
| 1089 | n/a | fpname, lineno) |
|---|
| 1090 | n/a | elements_added.add((sectname, optname)) |
|---|
| 1091 | n/a | # This check is fine because the OPTCRE cannot |
|---|
| 1092 | n/a | # match if it would set optval to None |
|---|
| 1093 | n/a | if optval is not None: |
|---|
| 1094 | n/a | optval = optval.strip() |
|---|
| 1095 | n/a | cursect[optname] = [optval] |
|---|
| 1096 | n/a | else: |
|---|
| 1097 | n/a | # valueless option handling |
|---|
| 1098 | n/a | cursect[optname] = None |
|---|
| 1099 | n/a | else: |
|---|
| 1100 | n/a | # a non-fatal parsing error occurred. set up the |
|---|
| 1101 | n/a | # exception but keep going. the exception will be |
|---|
| 1102 | n/a | # raised at the end of the file and will contain a |
|---|
| 1103 | n/a | # list of all bogus lines |
|---|
| 1104 | n/a | e = self._handle_error(e, fpname, lineno, line) |
|---|
| 1105 | n/a | self._join_multiline_values() |
|---|
| 1106 | n/a | # if any parsing errors occurred, raise an exception |
|---|
| 1107 | n/a | if e: |
|---|
| 1108 | n/a | raise e |
|---|
| 1109 | n/a | |
|---|
| 1110 | n/a | def _join_multiline_values(self): |
|---|
| 1111 | n/a | defaults = self.default_section, self._defaults |
|---|
| 1112 | n/a | all_sections = itertools.chain((defaults,), |
|---|
| 1113 | n/a | self._sections.items()) |
|---|
| 1114 | n/a | for section, options in all_sections: |
|---|
| 1115 | n/a | for name, val in options.items(): |
|---|
| 1116 | n/a | if isinstance(val, list): |
|---|
| 1117 | n/a | val = '\n'.join(val).rstrip() |
|---|
| 1118 | n/a | options[name] = self._interpolation.before_read(self, |
|---|
| 1119 | n/a | section, |
|---|
| 1120 | n/a | name, val) |
|---|
| 1121 | n/a | |
|---|
| 1122 | n/a | def _handle_error(self, exc, fpname, lineno, line): |
|---|
| 1123 | n/a | if not exc: |
|---|
| 1124 | n/a | exc = ParsingError(fpname) |
|---|
| 1125 | n/a | exc.append(lineno, repr(line)) |
|---|
| 1126 | n/a | return exc |
|---|
| 1127 | n/a | |
|---|
| 1128 | n/a | def _unify_values(self, section, vars): |
|---|
| 1129 | n/a | """Create a sequence of lookups with 'vars' taking priority over |
|---|
| 1130 | n/a | the 'section' which takes priority over the DEFAULTSECT. |
|---|
| 1131 | n/a | |
|---|
| 1132 | n/a | """ |
|---|
| 1133 | n/a | sectiondict = {} |
|---|
| 1134 | n/a | try: |
|---|
| 1135 | n/a | sectiondict = self._sections[section] |
|---|
| 1136 | n/a | except KeyError: |
|---|
| 1137 | n/a | if section != self.default_section: |
|---|
| 1138 | n/a | raise NoSectionError(section) |
|---|
| 1139 | n/a | # Update with the entry specific variables |
|---|
| 1140 | n/a | vardict = {} |
|---|
| 1141 | n/a | if vars: |
|---|
| 1142 | n/a | for key, value in vars.items(): |
|---|
| 1143 | n/a | if value is not None: |
|---|
| 1144 | n/a | value = str(value) |
|---|
| 1145 | n/a | vardict[self.optionxform(key)] = value |
|---|
| 1146 | n/a | return _ChainMap(vardict, sectiondict, self._defaults) |
|---|
| 1147 | n/a | |
|---|
| 1148 | n/a | def _convert_to_boolean(self, value): |
|---|
| 1149 | n/a | """Return a boolean value translating from other types if necessary. |
|---|
| 1150 | n/a | """ |
|---|
| 1151 | n/a | if value.lower() not in self.BOOLEAN_STATES: |
|---|
| 1152 | n/a | raise ValueError('Not a boolean: %s' % value) |
|---|
| 1153 | n/a | return self.BOOLEAN_STATES[value.lower()] |
|---|
| 1154 | n/a | |
|---|
| 1155 | n/a | def _validate_value_types(self, *, section="", option="", value=""): |
|---|
| 1156 | n/a | """Raises a TypeError for non-string values. |
|---|
| 1157 | n/a | |
|---|
| 1158 | n/a | The only legal non-string value if we allow valueless |
|---|
| 1159 | n/a | options is None, so we need to check if the value is a |
|---|
| 1160 | n/a | string if: |
|---|
| 1161 | n/a | - we do not allow valueless options, or |
|---|
| 1162 | n/a | - we allow valueless options but the value is not None |
|---|
| 1163 | n/a | |
|---|
| 1164 | n/a | For compatibility reasons this method is not used in classic set() |
|---|
| 1165 | n/a | for RawConfigParsers. It is invoked in every case for mapping protocol |
|---|
| 1166 | n/a | access and in ConfigParser.set(). |
|---|
| 1167 | n/a | """ |
|---|
| 1168 | n/a | if not isinstance(section, str): |
|---|
| 1169 | n/a | raise TypeError("section names must be strings") |
|---|
| 1170 | n/a | if not isinstance(option, str): |
|---|
| 1171 | n/a | raise TypeError("option keys must be strings") |
|---|
| 1172 | n/a | if not self._allow_no_value or value: |
|---|
| 1173 | n/a | if not isinstance(value, str): |
|---|
| 1174 | n/a | raise TypeError("option values must be strings") |
|---|
| 1175 | n/a | |
|---|
| 1176 | n/a | @property |
|---|
| 1177 | n/a | def converters(self): |
|---|
| 1178 | n/a | return self._converters |
|---|
| 1179 | n/a | |
|---|
| 1180 | n/a | |
|---|
| 1181 | n/a | class ConfigParser(RawConfigParser): |
|---|
| 1182 | n/a | """ConfigParser implementing interpolation.""" |
|---|
| 1183 | n/a | |
|---|
| 1184 | n/a | _DEFAULT_INTERPOLATION = BasicInterpolation() |
|---|
| 1185 | n/a | |
|---|
| 1186 | n/a | def set(self, section, option, value=None): |
|---|
| 1187 | n/a | """Set an option. Extends RawConfigParser.set by validating type and |
|---|
| 1188 | n/a | interpolation syntax on the value.""" |
|---|
| 1189 | n/a | self._validate_value_types(option=option, value=value) |
|---|
| 1190 | n/a | super().set(section, option, value) |
|---|
| 1191 | n/a | |
|---|
| 1192 | n/a | def add_section(self, section): |
|---|
| 1193 | n/a | """Create a new section in the configuration. Extends |
|---|
| 1194 | n/a | RawConfigParser.add_section by validating if the section name is |
|---|
| 1195 | n/a | a string.""" |
|---|
| 1196 | n/a | self._validate_value_types(section=section) |
|---|
| 1197 | n/a | super().add_section(section) |
|---|
| 1198 | n/a | |
|---|
| 1199 | n/a | |
|---|
| 1200 | n/a | class SafeConfigParser(ConfigParser): |
|---|
| 1201 | n/a | """ConfigParser alias for backwards compatibility purposes.""" |
|---|
| 1202 | n/a | |
|---|
| 1203 | n/a | def __init__(self, *args, **kwargs): |
|---|
| 1204 | n/a | super().__init__(*args, **kwargs) |
|---|
| 1205 | n/a | warnings.warn( |
|---|
| 1206 | n/a | "The SafeConfigParser class has been renamed to ConfigParser " |
|---|
| 1207 | n/a | "in Python 3.2. This alias will be removed in future versions." |
|---|
| 1208 | n/a | " Use ConfigParser directly instead.", |
|---|
| 1209 | n/a | DeprecationWarning, stacklevel=2 |
|---|
| 1210 | n/a | ) |
|---|
| 1211 | n/a | |
|---|
| 1212 | n/a | |
|---|
| 1213 | n/a | class SectionProxy(MutableMapping): |
|---|
| 1214 | n/a | """A proxy for a single section from a parser.""" |
|---|
| 1215 | n/a | |
|---|
| 1216 | n/a | def __init__(self, parser, name): |
|---|
| 1217 | n/a | """Creates a view on a section of the specified `name` in `parser`.""" |
|---|
| 1218 | n/a | self._parser = parser |
|---|
| 1219 | n/a | self._name = name |
|---|
| 1220 | n/a | for conv in parser.converters: |
|---|
| 1221 | n/a | key = 'get' + conv |
|---|
| 1222 | n/a | getter = functools.partial(self.get, _impl=getattr(parser, key)) |
|---|
| 1223 | n/a | setattr(self, key, getter) |
|---|
| 1224 | n/a | |
|---|
| 1225 | n/a | def __repr__(self): |
|---|
| 1226 | n/a | return '<Section: {}>'.format(self._name) |
|---|
| 1227 | n/a | |
|---|
| 1228 | n/a | def __getitem__(self, key): |
|---|
| 1229 | n/a | if not self._parser.has_option(self._name, key): |
|---|
| 1230 | n/a | raise KeyError(key) |
|---|
| 1231 | n/a | return self._parser.get(self._name, key) |
|---|
| 1232 | n/a | |
|---|
| 1233 | n/a | def __setitem__(self, key, value): |
|---|
| 1234 | n/a | self._parser._validate_value_types(option=key, value=value) |
|---|
| 1235 | n/a | return self._parser.set(self._name, key, value) |
|---|
| 1236 | n/a | |
|---|
| 1237 | n/a | def __delitem__(self, key): |
|---|
| 1238 | n/a | if not (self._parser.has_option(self._name, key) and |
|---|
| 1239 | n/a | self._parser.remove_option(self._name, key)): |
|---|
| 1240 | n/a | raise KeyError(key) |
|---|
| 1241 | n/a | |
|---|
| 1242 | n/a | def __contains__(self, key): |
|---|
| 1243 | n/a | return self._parser.has_option(self._name, key) |
|---|
| 1244 | n/a | |
|---|
| 1245 | n/a | def __len__(self): |
|---|
| 1246 | n/a | return len(self._options()) |
|---|
| 1247 | n/a | |
|---|
| 1248 | n/a | def __iter__(self): |
|---|
| 1249 | n/a | return self._options().__iter__() |
|---|
| 1250 | n/a | |
|---|
| 1251 | n/a | def _options(self): |
|---|
| 1252 | n/a | if self._name != self._parser.default_section: |
|---|
| 1253 | n/a | return self._parser.options(self._name) |
|---|
| 1254 | n/a | else: |
|---|
| 1255 | n/a | return self._parser.defaults() |
|---|
| 1256 | n/a | |
|---|
| 1257 | n/a | @property |
|---|
| 1258 | n/a | def parser(self): |
|---|
| 1259 | n/a | # The parser object of the proxy is read-only. |
|---|
| 1260 | n/a | return self._parser |
|---|
| 1261 | n/a | |
|---|
| 1262 | n/a | @property |
|---|
| 1263 | n/a | def name(self): |
|---|
| 1264 | n/a | # The name of the section on a proxy is read-only. |
|---|
| 1265 | n/a | return self._name |
|---|
| 1266 | n/a | |
|---|
| 1267 | n/a | def get(self, option, fallback=None, *, raw=False, vars=None, |
|---|
| 1268 | n/a | _impl=None, **kwargs): |
|---|
| 1269 | n/a | """Get an option value. |
|---|
| 1270 | n/a | |
|---|
| 1271 | n/a | Unless `fallback` is provided, `None` will be returned if the option |
|---|
| 1272 | n/a | is not found. |
|---|
| 1273 | n/a | |
|---|
| 1274 | n/a | """ |
|---|
| 1275 | n/a | # If `_impl` is provided, it should be a getter method on the parser |
|---|
| 1276 | n/a | # object that provides the desired type conversion. |
|---|
| 1277 | n/a | if not _impl: |
|---|
| 1278 | n/a | _impl = self._parser.get |
|---|
| 1279 | n/a | return _impl(self._name, option, raw=raw, vars=vars, |
|---|
| 1280 | n/a | fallback=fallback, **kwargs) |
|---|
| 1281 | n/a | |
|---|
| 1282 | n/a | |
|---|
| 1283 | n/a | class ConverterMapping(MutableMapping): |
|---|
| 1284 | n/a | """Enables reuse of get*() methods between the parser and section proxies. |
|---|
| 1285 | n/a | |
|---|
| 1286 | n/a | If a parser class implements a getter directly, the value for the given |
|---|
| 1287 | n/a | key will be ``None``. The presence of the converter name here enables |
|---|
| 1288 | n/a | section proxies to find and use the implementation on the parser class. |
|---|
| 1289 | n/a | """ |
|---|
| 1290 | n/a | |
|---|
| 1291 | n/a | GETTERCRE = re.compile(r"^get(?P<name>.+)$") |
|---|
| 1292 | n/a | |
|---|
| 1293 | n/a | def __init__(self, parser): |
|---|
| 1294 | n/a | self._parser = parser |
|---|
| 1295 | n/a | self._data = {} |
|---|
| 1296 | n/a | for getter in dir(self._parser): |
|---|
| 1297 | n/a | m = self.GETTERCRE.match(getter) |
|---|
| 1298 | n/a | if not m or not callable(getattr(self._parser, getter)): |
|---|
| 1299 | n/a | continue |
|---|
| 1300 | n/a | self._data[m.group('name')] = None # See class docstring. |
|---|
| 1301 | n/a | |
|---|
| 1302 | n/a | def __getitem__(self, key): |
|---|
| 1303 | n/a | return self._data[key] |
|---|
| 1304 | n/a | |
|---|
| 1305 | n/a | def __setitem__(self, key, value): |
|---|
| 1306 | n/a | try: |
|---|
| 1307 | n/a | k = 'get' + key |
|---|
| 1308 | n/a | except TypeError: |
|---|
| 1309 | n/a | raise ValueError('Incompatible key: {} (type: {})' |
|---|
| 1310 | n/a | ''.format(key, type(key))) |
|---|
| 1311 | n/a | if k == 'get': |
|---|
| 1312 | n/a | raise ValueError('Incompatible key: cannot use "" as a name') |
|---|
| 1313 | n/a | self._data[key] = value |
|---|
| 1314 | n/a | func = functools.partial(self._parser._get_conv, conv=value) |
|---|
| 1315 | n/a | func.converter = value |
|---|
| 1316 | n/a | setattr(self._parser, k, func) |
|---|
| 1317 | n/a | for proxy in self._parser.values(): |
|---|
| 1318 | n/a | getter = functools.partial(proxy.get, _impl=func) |
|---|
| 1319 | n/a | setattr(proxy, k, getter) |
|---|
| 1320 | n/a | |
|---|
| 1321 | n/a | def __delitem__(self, key): |
|---|
| 1322 | n/a | try: |
|---|
| 1323 | n/a | k = 'get' + (key or None) |
|---|
| 1324 | n/a | except TypeError: |
|---|
| 1325 | n/a | raise KeyError(key) |
|---|
| 1326 | n/a | del self._data[key] |
|---|
| 1327 | n/a | for inst in itertools.chain((self._parser,), self._parser.values()): |
|---|
| 1328 | n/a | try: |
|---|
| 1329 | n/a | delattr(inst, k) |
|---|
| 1330 | n/a | except AttributeError: |
|---|
| 1331 | n/a | # don't raise since the entry was present in _data, silently |
|---|
| 1332 | n/a | # clean up |
|---|
| 1333 | n/a | continue |
|---|
| 1334 | n/a | |
|---|
| 1335 | n/a | def __iter__(self): |
|---|
| 1336 | n/a | return iter(self._data) |
|---|
| 1337 | n/a | |
|---|
| 1338 | n/a | def __len__(self): |
|---|
| 1339 | n/a | return len(self._data) |
|---|