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