|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +import ConfigParser |
| 3 | +import re |
| 4 | + |
| 5 | +""" |
| 6 | +Allows use of square brackets in .ini section names, which are used in some globs. |
| 7 | +Based off of python 2.6 ConfigParser.RawConfigParser source code with a few modifications. |
| 8 | +http://hg.python.org/cpython/file/8c4d42c0dc8e/Lib/configparser.py |
| 9 | +""" |
| 10 | +class GlobSafeConfigParser(ConfigParser.RawConfigParser): |
| 11 | + |
| 12 | + OPTCRE = re.compile( |
| 13 | + r'(?P<option>[^:=\s][^:=]*)' |
| 14 | + r'\s*(?P<vi>[:=])\s*' |
| 15 | + r'(?P<value>.*)$' |
| 16 | + ) |
| 17 | + |
| 18 | + def _read(self, fp, fpname): |
| 19 | + cursect = None |
| 20 | + optname = None |
| 21 | + lineno = 0 |
| 22 | + e = None |
| 23 | + while True: |
| 24 | + line = fp.readline() |
| 25 | + if not line: |
| 26 | + break |
| 27 | + lineno = lineno + 1 |
| 28 | + if line.strip() == '' or line[0] in '#;': |
| 29 | + continue |
| 30 | + if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR": |
| 31 | + continue |
| 32 | + if line[0].isspace() and cursect is not None and optname: |
| 33 | + value = line.strip() |
| 34 | + if value: |
| 35 | + cursect[optname] = "%s\n%s" % (cursect[optname], value) |
| 36 | + else: |
| 37 | + try: |
| 38 | + value = line[:line.index(';')].strip() |
| 39 | + except ValueError: |
| 40 | + value = line.strip() |
| 41 | + |
| 42 | + if value[0]=='[' and value[-1]==']' and len(value)>2: |
| 43 | + sectname = value[1:-1] |
| 44 | + if sectname in self._sections: |
| 45 | + cursect = self._sections[sectname] |
| 46 | + elif sectname == "DEFAULT": |
| 47 | + cursect = self._defaults |
| 48 | + else: |
| 49 | + cursect = self._dict() |
| 50 | + cursect['__name__'] = sectname |
| 51 | + self._sections[sectname] = cursect |
| 52 | + optname = None |
| 53 | + elif cursect is None: |
| 54 | + raise MissingSectionHeaderError(fpname, lineno, line) |
| 55 | + else: |
| 56 | + mo = self.OPTCRE.match(line) |
| 57 | + if mo: |
| 58 | + optname, vi, optval = mo.group('option', 'vi', 'value') |
| 59 | + if vi in ('=', ':') and ';' in optval: |
| 60 | + pos = optval.find(';') |
| 61 | + if pos != -1 and optval[pos-1].isspace(): |
| 62 | + optval = optval[:pos] |
| 63 | + optval = optval.strip() |
| 64 | + if optval == '""': |
| 65 | + optval = '' |
| 66 | + optname = self.optionxform(optname.rstrip()) |
| 67 | + cursect[optname] = optval |
| 68 | + else: |
| 69 | + if not e: |
| 70 | + e = ParsingError(fpname) |
| 71 | + e.append(lineno, repr(line)) |
| 72 | + if e: |
| 73 | + raise e |
0 commit comments