__init__.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. """ brain-dead simple parser for ini-style files.
  2. (C) Ronny Pfannschmidt, Holger Krekel -- MIT licensed
  3. """
  4. __all__ = ['IniConfig', 'ParseError']
  5. COMMENTCHARS = "#;"
  6. class ParseError(Exception):
  7. def __init__(self, path, lineno, msg):
  8. Exception.__init__(self, path, lineno, msg)
  9. self.path = path
  10. self.lineno = lineno
  11. self.msg = msg
  12. def __str__(self):
  13. return "%s:%s: %s" % (self.path, self.lineno+1, self.msg)
  14. class SectionWrapper(object):
  15. def __init__(self, config, name):
  16. self.config = config
  17. self.name = name
  18. def lineof(self, name):
  19. return self.config.lineof(self.name, name)
  20. def get(self, key, default=None, convert=str):
  21. return self.config.get(self.name, key,
  22. convert=convert, default=default)
  23. def __getitem__(self, key):
  24. return self.config.sections[self.name][key]
  25. def __iter__(self):
  26. section = self.config.sections.get(self.name, [])
  27. def lineof(key):
  28. return self.config.lineof(self.name, key)
  29. for name in sorted(section, key=lineof):
  30. yield name
  31. def items(self):
  32. for name in self:
  33. yield name, self[name]
  34. class IniConfig(object):
  35. def __init__(self, path, data=None):
  36. self.path = str(path) # convenience
  37. if data is None:
  38. f = open(self.path)
  39. try:
  40. tokens = self._parse(iter(f))
  41. finally:
  42. f.close()
  43. else:
  44. tokens = self._parse(data.splitlines(True))
  45. self._sources = {}
  46. self.sections = {}
  47. for lineno, section, name, value in tokens:
  48. if section is None:
  49. self._raise(lineno, 'no section header defined')
  50. self._sources[section, name] = lineno
  51. if name is None:
  52. if section in self.sections:
  53. self._raise(lineno, 'duplicate section %r' % (section, ))
  54. self.sections[section] = {}
  55. else:
  56. if name in self.sections[section]:
  57. self._raise(lineno, 'duplicate name %r' % (name, ))
  58. self.sections[section][name] = value
  59. def _raise(self, lineno, msg):
  60. raise ParseError(self.path, lineno, msg)
  61. def _parse(self, line_iter):
  62. result = []
  63. section = None
  64. for lineno, line in enumerate(line_iter):
  65. name, data = self._parseline(line, lineno)
  66. # new value
  67. if name is not None and data is not None:
  68. result.append((lineno, section, name, data))
  69. # new section
  70. elif name is not None and data is None:
  71. if not name:
  72. self._raise(lineno, 'empty section name')
  73. section = name
  74. result.append((lineno, section, None, None))
  75. # continuation
  76. elif name is None and data is not None:
  77. if not result:
  78. self._raise(lineno, 'unexpected value continuation')
  79. last = result.pop()
  80. last_name, last_data = last[-2:]
  81. if last_name is None:
  82. self._raise(lineno, 'unexpected value continuation')
  83. if last_data:
  84. data = '%s\n%s' % (last_data, data)
  85. result.append(last[:-1] + (data,))
  86. return result
  87. def _parseline(self, line, lineno):
  88. # blank lines
  89. if iscommentline(line):
  90. line = ""
  91. else:
  92. line = line.rstrip()
  93. if not line:
  94. return None, None
  95. # section
  96. if line[0] == '[':
  97. realline = line
  98. for c in COMMENTCHARS:
  99. line = line.split(c)[0].rstrip()
  100. if line[-1] == "]":
  101. return line[1:-1], None
  102. return None, realline.strip()
  103. # value
  104. elif not line[0].isspace():
  105. try:
  106. name, value = line.split('=', 1)
  107. if ":" in name:
  108. raise ValueError()
  109. except ValueError:
  110. try:
  111. name, value = line.split(":", 1)
  112. except ValueError:
  113. self._raise(lineno, 'unexpected line: %r' % line)
  114. return name.strip(), value.strip()
  115. # continuation
  116. else:
  117. return None, line.strip()
  118. def lineof(self, section, name=None):
  119. lineno = self._sources.get((section, name))
  120. if lineno is not None:
  121. return lineno + 1
  122. def get(self, section, name, default=None, convert=str):
  123. try:
  124. return convert(self.sections[section][name])
  125. except KeyError:
  126. return default
  127. def __getitem__(self, name):
  128. if name not in self.sections:
  129. raise KeyError(name)
  130. return SectionWrapper(self, name)
  131. def __iter__(self):
  132. for name in sorted(self.sections, key=self.lineof):
  133. yield SectionWrapper(self, name)
  134. def __contains__(self, arg):
  135. return arg in self.sections
  136. def iscommentline(line):
  137. c = line.lstrip()[:1]
  138. return c in COMMENTCHARS