more Markdown stuff
[synarere.git] / core / confparse.py
blobc1243db33cd32cf38b00f40db3d28ccbfde08cb4
1 # synarere -- a highly modular and stable IRC bot.
2 # Copyright (C) 2010 Michael Rodriguez.
3 # Rights to this code are documented in docs/LICENSE.
5 '''Configuration parser.'''
7 # Import required Python module.
8 import os
10 # Import required source modules.
11 import logger, irc, var, event
13 class ConfigBlock(object):
14 def __init__ (self, label, values={}):
15 self.label = label
16 self.vars = {}
18 # Copy over any values given during initialization
19 for key in values:
20 self.vars[key] = values[key]
22 def add (self, name, value):
23 self.vars[name] = value
25 def get (self, name, defval=None):
26 return self.vars.get(name, defval)
28 class ConfigParser:
29 def __init__(self, file):
30 self.file = file
31 self.parse()
33 def rehash(self, on_sighup):
34 '''Rehash configuration and change synarere to fit the new conditions.'''
36 logger.info('Rehashing configuration %s' % ('due to SIGHUP.' if on_sighup else ''))
37 self.parse()
39 event.dispatch('OnRehash', self.file, on_sighup)
41 def parse(self):
42 '''Parse our file, and put the data into a dictionary.'''
44 lno = 0
46 # Attempt to open the file.
47 fh = open(self.file, 'r')
49 # Parse.
50 self.blocks = []
52 for line in fh.xreadlines():
53 for cno, c in enumerate(line):
54 if c == '\n':
55 # Increment the line number.
56 lno += 1
58 if c == '#': # Comment until EOL.
59 break
60 if c == ':': # Block label.
61 label = line[:cno].strip()
62 self.blocks.append(ConfigBlock(label))
63 if c == '=': # Variable.
64 if not self.blocks: # Skip this line, as no block label was given yet.
65 break
66 varname = line[:cno].strip()
67 varval = line[cno + 1:].strip()
68 self.blocks[-1].add(varname, varval)
69 break
71 # Close the file handle
72 fh.close()
74 def xget(self, block, variable=None):
75 '''
76 Return whatever is in block:variable. If variable is None,
77 we will iterate over mutiple blocks, thus allowing us to
78 return multiple values from multiple blocks.
79 '''
81 if block not in set(b.label for b in self.blocks):
82 logger.debug('%r block not in configuration.' % block)
84 for i in self.blocks:
85 if i.label == block:
86 if variable is None: # Just get blocks by this name
87 yield i
88 else: # Get a member of blocks by this name.
89 yield i.get(variable)
91 def get(self, block, variable=None):
92 '''
93 Call our iterating generator (xget) and just store all its
94 results into a list to return all at once.
95 '''
97 return [b for b in self.xget(block, variable)]