|
161 | 161 | "InterpolationMissingOptionError", "InterpolationSyntaxError", |
162 | 162 | "ParsingError", "MissingSectionHeaderError", |
163 | 163 | "MultilineContinuationError", "UnnamedSectionDisabledError", |
164 | | - "ConfigParser", "RawConfigParser", |
| 164 | + "InvalidWriteError", "ConfigParser", "RawConfigParser", |
165 | 165 | "Interpolation", "BasicInterpolation", "ExtendedInterpolation", |
166 | 166 | "SectionProxy", "ConverterMapping", |
167 | 167 | "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH", "UNNAMED_SECTION") |
@@ -375,6 +375,14 @@ class _UnnamedSection: |
375 | 375 | def __repr__(self): |
376 | 376 | return "<UNNAMED_SECTION>" |
377 | 377 |
|
| 378 | +class InvalidWriteError(Error): |
| 379 | + """Raised when attempting to write data that the parser would read back differently. |
| 380 | + ex: writing a key which begins with the section header pattern would read back as a |
| 381 | + new section """ |
| 382 | + |
| 383 | + def __init__(self, msg=''): |
| 384 | + Error.__init__(self, msg) |
| 385 | + |
378 | 386 |
|
379 | 387 | UNNAMED_SECTION = _UnnamedSection() |
380 | 388 |
|
@@ -973,6 +981,7 @@ def _write_section(self, fp, section_name, section_items, delimiter, unnamed=Fal |
973 | 981 | if not unnamed: |
974 | 982 | fp.write("[{}]\n".format(section_name)) |
975 | 983 | for key, value in section_items: |
| 984 | + self._validate_key_contents(key) |
976 | 985 | value = self._interpolation.before_write(self, section_name, key, |
977 | 986 | value) |
978 | 987 | if value is not None or not self._allow_no_value: |
@@ -1210,6 +1219,14 @@ def _convert_to_boolean(self, value): |
1210 | 1219 | raise ValueError('Not a boolean: %s' % value) |
1211 | 1220 | return self.BOOLEAN_STATES[value.lower()] |
1212 | 1221 |
|
| 1222 | + def _validate_key_contents(self, key): |
| 1223 | + """Raises an InvalidWriteError for any keys containing |
| 1224 | + delimiters or that match the section header pattern""" |
| 1225 | + if re.match(self.SECTCRE, key): |
| 1226 | + raise InvalidWriteError("Cannot write keys matching section pattern") |
| 1227 | + if any(delim in key for delim in self._delimiters): |
| 1228 | + raise InvalidWriteError("Cannot write key that contains delimiters") |
| 1229 | + |
1213 | 1230 | def _validate_value_types(self, *, section="", option="", value=""): |
1214 | 1231 | """Raises a TypeError for illegal non-string values. |
1215 | 1232 |
|
|
0 commit comments