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.
10 # Import required source modules.
11 import logger
, irc
, var
, event
13 class ConfigBlock(object):
14 def __init__ (self
, label
, values
={}):
18 # Copy over any values given during initialization
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
)
29 def __init__(self
, file):
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 ''))
39 event
.dispatch('OnRehash', self
.file, on_sighup
)
42 '''Parse our file, and put the data into a dictionary.'''
46 # Attempt to open the file.
47 fh
= open(self
.file, 'r')
52 for line
in fh
.xreadlines():
53 for cno
, c
in enumerate(line
):
55 # Increment the line number.
58 if c
== '#': # Comment until EOL.
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.
66 varname
= line
[:cno
].strip()
67 varval
= line
[cno
+ 1:].strip()
68 self
.blocks
[-1].add(varname
, varval
)
71 # Close the file handle
74 def xget(self
, block
, variable
=None):
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.
81 if block
not in set(b
.label
for b
in self
.blocks
):
82 logger
.debug('%r block not in configuration.' % block
)
86 if variable
is None: # Just get blocks by this name
88 else: # Get a member of blocks by this name.
91 def get(self
, block
, variable
=None):
93 Call our iterating generator (xget) and just store all its
94 results into a list to return all at once.
97 return [b
for b
in self
.xget(block
, variable
)]