astconfigparser.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. import re
  2. import itertools
  3. from astdicts import OrderedDict
  4. from astdicts import MultiOrderedDict
  5. def merge_values(left, right, key):
  6. """Merges values from right into left."""
  7. if isinstance(left, list):
  8. vals0 = left
  9. else: # assume dictionary
  10. vals0 = left[key] if key in left else []
  11. vals1 = right[key] if key in right else []
  12. return vals0 + [i for i in vals1 if i not in vals0]
  13. ###############################################################################
  14. class Section(MultiOrderedDict):
  15. """
  16. A Section is a MultiOrderedDict itself that maintains a list of
  17. key/value options. However, in the case of an Asterisk config
  18. file a section may have other defaults sections that is can pull
  19. data from (i.e. templates). So when an option is looked up by key
  20. it first checks the base section and if not found looks in the
  21. added default sections. If not found at that point then a 'KeyError'
  22. exception is raised.
  23. """
  24. count = 0
  25. def __init__(self, defaults=None, templates=None):
  26. MultiOrderedDict.__init__(self)
  27. # track an ordered id of sections
  28. Section.count += 1
  29. self.id = Section.count
  30. self._defaults = [] if defaults is None else defaults
  31. self._templates = [] if templates is None else templates
  32. def __cmp__(self, other):
  33. """
  34. Use self.id as means of determining equality
  35. """
  36. return cmp(self.id, other.id)
  37. def get(self, key, from_self=True, from_templates=True,
  38. from_defaults=True):
  39. """
  40. Get the values corresponding to a given key. The parameters to this
  41. function form a hierarchy that determines priority of the search.
  42. from_self takes priority over from_templates, and from_templates takes
  43. priority over from_defaults.
  44. Parameters:
  45. from_self - If True, search within the given section.
  46. from_templates - If True, search in this section's templates.
  47. from_defaults - If True, search within this section's defaults.
  48. """
  49. if from_self and key in self:
  50. return MultiOrderedDict.__getitem__(self, key)
  51. if from_templates:
  52. if self in self._templates:
  53. return []
  54. for t in self._templates:
  55. try:
  56. # fail if not found on the search - doing it this way
  57. # allows template's templates to be searched.
  58. return t.get(key, True, from_templates, from_defaults)
  59. except KeyError:
  60. pass
  61. if from_defaults:
  62. for d in self._defaults:
  63. try:
  64. return d.get(key, True, from_templates, from_defaults)
  65. except KeyError:
  66. pass
  67. raise KeyError(key)
  68. def __getitem__(self, key):
  69. """
  70. Get the value for the given key. If it is not found in the 'self'
  71. then check inside templates and defaults before declaring raising
  72. a KeyError exception.
  73. """
  74. return self.get(key)
  75. def keys(self, self_only=False):
  76. """
  77. Get the keys from this section. If self_only is True, then
  78. keys from this section's defaults and templates are not
  79. included in the returned value
  80. """
  81. res = MultiOrderedDict.keys(self)
  82. if self_only:
  83. return res
  84. for d in self._templates:
  85. for key in d.keys():
  86. if key not in res:
  87. res.append(key)
  88. for d in self._defaults:
  89. for key in d.keys():
  90. if key not in res:
  91. res.append(key)
  92. return res
  93. def add_defaults(self, defaults):
  94. """
  95. Add a list of defaults to the section. Defaults are
  96. sections such as 'general'
  97. """
  98. defaults.sort()
  99. for i in defaults:
  100. self._defaults.insert(0, i)
  101. def add_templates(self, templates):
  102. """
  103. Add a list of templates to the section.
  104. """
  105. templates.sort()
  106. for i in templates:
  107. self._templates.insert(0, i)
  108. def get_merged(self, key):
  109. """Return a list of values for a given key merged from default(s)"""
  110. # first merge key/values from defaults together
  111. merged = []
  112. for i in reversed(self._defaults):
  113. if not merged:
  114. merged = i
  115. continue
  116. merged = merge_values(merged, i, key)
  117. for i in reversed(self._templates):
  118. if not merged:
  119. merged = i
  120. continue
  121. merged = merge_values(merged, i, key)
  122. # then merge self in
  123. return merge_values(merged, self, key)
  124. ###############################################################################
  125. COMMENT = ';'
  126. COMMENT_START = ';--'
  127. COMMENT_END = '--;'
  128. DEFAULTSECT = 'general'
  129. def remove_comment(line, is_comment):
  130. """Remove any commented elements from the line."""
  131. if not line:
  132. return line, is_comment
  133. if is_comment:
  134. part = line.partition(COMMENT_END)
  135. if part[1]:
  136. # found multi-line comment end check string after it
  137. return remove_comment(part[2], False)
  138. return "", True
  139. part = line.partition(COMMENT_START)
  140. if part[1]:
  141. # found multi-line comment start check string before
  142. # it to make sure there wasn't an eol comment in it
  143. has_comment = part[0].partition(COMMENT)
  144. if has_comment[1]:
  145. # eol comment found return anything before it
  146. return has_comment[0], False
  147. # check string after it to see if the comment ends
  148. line, is_comment = remove_comment(part[2], True)
  149. if is_comment:
  150. # return possible string data before comment
  151. return part[0].strip(), True
  152. # otherwise it was an embedded comment so combine
  153. return ''.join([part[0].strip(), ' ', line]).rstrip(), False
  154. # check for eol comment
  155. return line.partition(COMMENT)[0].strip(), False
  156. def try_include(line):
  157. """
  158. Checks to see if the given line is an include. If so return the
  159. included filename, otherwise None.
  160. """
  161. match = re.match('^#include\s*[<"]?(.*)[>"]?$', line)
  162. return match.group(1) if match else None
  163. def try_section(line):
  164. """
  165. Checks to see if the given line is a section. If so return the section
  166. name, otherwise return 'None'.
  167. """
  168. # leading spaces were stripped when checking for comments
  169. if not line.startswith('['):
  170. return None, False, []
  171. section, delim, templates = line.partition(']')
  172. if not templates:
  173. return section[1:], False, []
  174. # strip out the parens and parse into an array
  175. templates = templates.replace('(', "").replace(')', "").split(',')
  176. # go ahead and remove extra whitespace
  177. templates = [i.strip() for i in templates]
  178. try:
  179. templates.remove('!')
  180. return section[1:], True, templates
  181. except:
  182. return section[1:], False, templates
  183. def try_option(line):
  184. """Parses the line as an option, returning the key/value pair."""
  185. data = re.split('=>?', line)
  186. # should split in two (key/val), but either way use first two elements
  187. return data[0].rstrip(), data[1].lstrip()
  188. ###############################################################################
  189. def find_dict(mdicts, key, val):
  190. """
  191. Given a list of mult-dicts, return the multi-dict that contains
  192. the given key/value pair.
  193. """
  194. def found(d):
  195. return key in d and val in d[key]
  196. try:
  197. return [d for d in mdicts if found(d)][0]
  198. except IndexError:
  199. raise LookupError("Dictionary not located for key = %s, value = %s"
  200. % (key, val))
  201. def write_dicts(config_file, mdicts):
  202. """Write the contents of the mdicts to the specified config file"""
  203. for section, sect_list in mdicts.iteritems():
  204. # every section contains a list of dictionaries
  205. for sect in sect_list:
  206. config_file.write("[%s]\n" % section)
  207. for key, val_list in sect.iteritems():
  208. # every value is also a list
  209. for v in val_list:
  210. key_val = key
  211. if v is not None:
  212. key_val += " = " + str(v)
  213. config_file.write("%s\n" % (key_val))
  214. config_file.write("\n")
  215. ###############################################################################
  216. class MultiOrderedConfigParser:
  217. def __init__(self, parent=None):
  218. self._parent = parent
  219. self._defaults = MultiOrderedDict()
  220. self._sections = MultiOrderedDict()
  221. self._includes = OrderedDict()
  222. def find_value(self, sections, key):
  223. """Given a list of sections, try to find value(s) for the given key."""
  224. # always start looking in the last one added
  225. sections.sort(reverse=True)
  226. for s in sections:
  227. try:
  228. # try to find in section and section's templates
  229. return s.get(key, from_defaults=False)
  230. except KeyError:
  231. pass
  232. # wasn't found in sections or a section's templates so check in
  233. # defaults
  234. for s in sections:
  235. try:
  236. # try to find in section's defaultsects
  237. return s.get(key, from_self=False, from_templates=False)
  238. except KeyError:
  239. pass
  240. raise KeyError(key)
  241. def defaults(self):
  242. return self._defaults
  243. def default(self, key):
  244. """Retrieves a list of dictionaries for a default section."""
  245. return self.get_defaults(key)
  246. def add_default(self, key, template_keys=None):
  247. """
  248. Adds a default section to defaults, returning the
  249. default Section object.
  250. """
  251. if template_keys is None:
  252. template_keys = []
  253. return self.add_section(key, template_keys, self._defaults)
  254. def sections(self):
  255. return self._sections
  256. def section(self, key):
  257. """Retrieves a list of dictionaries for a section."""
  258. return self.get_sections(key)
  259. def get_sections(self, key, attr='_sections', searched=None):
  260. """
  261. Retrieve a list of sections that have values for the given key.
  262. The attr parameter can be used to control what part of the parser
  263. to retrieve values from.
  264. """
  265. if searched is None:
  266. searched = []
  267. if self in searched:
  268. return []
  269. sections = getattr(self, attr)
  270. res = sections[key] if key in sections else []
  271. searched.append(self)
  272. if self._includes:
  273. res.extend(list(itertools.chain(*[
  274. incl.get_sections(key, attr, searched)
  275. for incl in self._includes.itervalues()])))
  276. if self._parent:
  277. res += self._parent.get_sections(key, attr, searched)
  278. return res
  279. def get_defaults(self, key):
  280. """
  281. Retrieve a list of defaults that have values for the given key.
  282. """
  283. return self.get_sections(key, '_defaults')
  284. def add_section(self, key, template_keys=None, mdicts=None):
  285. """
  286. Create a new section in the configuration. The name of the
  287. new section is the 'key' parameter.
  288. """
  289. if template_keys is None:
  290. template_keys = []
  291. if mdicts is None:
  292. mdicts = self._sections
  293. res = Section()
  294. for t in template_keys:
  295. res.add_templates(self.get_defaults(t))
  296. res.add_defaults(self.get_defaults(DEFAULTSECT))
  297. mdicts.insert(0, key, res)
  298. return res
  299. def includes(self):
  300. return self._includes
  301. def add_include(self, filename, parser=None):
  302. """
  303. Add a new #include file to the configuration.
  304. """
  305. if filename in self._includes:
  306. return self._includes[filename]
  307. self._includes[filename] = res = \
  308. MultiOrderedConfigParser(self) if parser is None else parser
  309. return res
  310. def get(self, section, key):
  311. """Retrieves the list of values from a section for a key."""
  312. try:
  313. # search for the value in the list of sections
  314. return self.find_value(self.section(section), key)
  315. except KeyError:
  316. pass
  317. try:
  318. # section may be a default section so, search
  319. # for the value in the list of defaults
  320. return self.find_value(self.default(section), key)
  321. except KeyError:
  322. raise LookupError("key %r not found for section %r"
  323. % (key, section))
  324. def multi_get(self, section, key_list):
  325. """
  326. Retrieves the list of values from a section for a list of keys.
  327. This method is intended to be used for equivalent keys. Thus, as soon
  328. as any match is found for any key in the key_list, the match is
  329. returned. This does not concatenate the lookups of all of the keys
  330. together.
  331. """
  332. for i in key_list:
  333. try:
  334. return self.get(section, i)
  335. except LookupError:
  336. pass
  337. # Making it here means all lookups failed.
  338. raise LookupError("keys %r not found for section %r" %
  339. (key_list, section))
  340. def set(self, section, key, val):
  341. """Sets an option in the given section."""
  342. # TODO - set in multiple sections? (for now set in first)
  343. # TODO - set in both sections and defaults?
  344. if section in self._sections:
  345. self.section(section)[0][key] = val
  346. else:
  347. self.defaults(section)[0][key] = val
  348. def read(self, filename, sect=None):
  349. """Parse configuration information from a file"""
  350. try:
  351. with open(filename, 'rt') as config_file:
  352. self._read(config_file, sect)
  353. except IOError:
  354. print "Could not open file ", filename, " for reading"
  355. def _read(self, config_file, sect):
  356. """Parse configuration information from the config_file"""
  357. is_comment = False # used for multi-lined comments
  358. for line in config_file:
  359. line, is_comment = remove_comment(line, is_comment)
  360. if not line:
  361. # line was empty or was a comment
  362. continue
  363. include_name = try_include(line)
  364. if include_name:
  365. parser = self.add_include(include_name)
  366. parser.read(include_name, sect)
  367. continue
  368. section, is_template, templates = try_section(line)
  369. if section:
  370. if section == DEFAULTSECT or is_template:
  371. sect = self.add_default(section, templates)
  372. else:
  373. sect = self.add_section(section, templates)
  374. continue
  375. key, val = try_option(line)
  376. if sect is None:
  377. raise Exception("Section not defined before assignment")
  378. sect[key] = val
  379. def write(self, config_file):
  380. """Write configuration information out to a file"""
  381. try:
  382. for key, val in self._includes.iteritems():
  383. val.write(key)
  384. config_file.write('#include "%s"\n' % key)
  385. config_file.write('\n')
  386. write_dicts(config_file, self._defaults)
  387. write_dicts(config_file, self._sections)
  388. except:
  389. try:
  390. with open(config_file, 'wt') as fp:
  391. self.write(fp)
  392. except IOError:
  393. print "Could not open file ", config_file, " for writing"