DirectoryParser() to parse config directories
[dbuscron] / dbuscron / parser.py
1 # encoding: utf-8
2 from __future__ import with_statement
3 import os
4 import re
5 from dbuscron.bus import DbusBus
6
7 def unescape_():
8     h = '[0-9A-Fa-f]'
9     r = re.compile(r'\\x('+h+r'{2})|\\u('+h+'{4})')
10
11     def unescape(value):
12         if not (value and
13                 (r'\x' in value or r'\u' in value)):
14             return value
15
16         return r.sub(
17             lambda m: chr(int(m.group(1), 16))
18                 if m.group(1) is not None else
19                     unichr(int(m.group(2), 16))
20                         .encode('utf-8'),\
21             value)
22     return unescape
23 unescape = unescape_()
24
25 def product(*args):
26     if args:
27         head, tail = args[0], args[1:]
28         for h in head:
29             for t in product(*tail):
30                 yield (h,) + t
31
32     else:
33         yield ()
34
35 class CrontabParserError(SyntaxError):
36     def __init__(self, message, lineno, expected=None):
37         if expected:
38             if isinstance(expected, (tuple, list)):
39                 exp = ' (expected %s or %s)' % (', '.join(expected[:-1]), expected[-1])
40         else:
41             exp = ''
42
43         msg = '%s%s at line %d' % (message, exp, lineno)
44
45         SyntaxError.__init__(self, msg)
46
47 class CrontabParser(object):
48     __fields_sep = re.compile(r'\s+')
49     __envvar_sep = re.compile(r'\s*=\s*')
50     __fields_chk = {
51             'bus_'         : None,
52             'type_'        : ('signal', 'method_call', 'method_return', 'error'),
53             'sender_'      : None,
54             'interface_'   : re.compile(r'^[a-zA-Z][a-zA-Z0-9_.]+$'),
55             'path_'        : re.compile(r'^/[a-zA-Z0-9_/]+$'),
56             'member_'      : re.compile(r'^[a-zA-Z][a-zA-Z0-9_]+$'),
57             'destination_' : None,
58             'args_'        : None,
59             }
60     __fields = [
61             'bus_',
62             'type_',
63             'sender_',
64             'interface_',
65             'path_',
66             'member_',
67             'destination_',
68             'args_',
69             ]
70
71     def __init__(self, fname):
72         self.__bus = DbusBus()
73         self.__filename = fname
74         self.__environ = dict()
75
76     @property
77     def environ(self):
78         return self.__environ
79
80     def _iterate_file(self, filename):
81         # bus type sender interface path member destination args command
82         lineno = 0
83         with open(filename) as f:
84             for line in f:
85                 lineno += 1
86                 line = line.strip()
87
88                 if not line or line.startswith('#'):
89                     continue
90
91                 parts = self.__fields_sep.split(line, 8)
92                 if len(parts) < 9:
93                     parts = self.__envvar_sep.split(line, 1)
94                     if len(parts) == 2:
95                         self.__environ[parts[0]] = parts[1]
96                         continue
97
98                     raise CrontabParserError('Unexpected number of records', lineno)
99
100                 rule = [('s', 'S'), self.__fields_chk['type_'], (None,), (None,), (None,), (None,), (None,), (None,)]
101
102                 for p in range(0, 8):
103                     if parts[p] != '*':
104                         rule[p] = parts[p].split(',')
105
106                 command = parts[8]
107
108                 for r in product(*rule):
109                     r = list(r)
110                     if r[0] == 'S':
111                         r[0] = self.__bus.system
112                     elif r[0] == 's':
113                         r[0] = self.__bus.session
114                     else:
115                         raise CrontabParserError('Unexpected bus value', lineno, expected=('S', 's', '*'))
116
117                     if r[7]:
118                         r[7] = map(unescape, r[7].split(';'))
119
120                     ruled = dict()
121                     for i, f in enumerate(self.__fields):
122                         if r[i] is not None and self.__fields_chk[f]:
123                             if isinstance(self.__fields_chk[f], tuple):
124                                 if r[i] not in self.__fields_chk[f]:
125                                     raise CrontabParserError('Unexpected %s value' % (f.strip('_')), lineno,
126                                             expected=self.__fields_chk[f])
127                             else:
128                                 if not self.__fields_chk[f].match(r[i]):
129                                     raise CrontabParserError('Incorrect %s value' % (f.strip('_')), lineno)
130                         ruled[f] = r[i]
131
132                     yield ruled, command
133
134     def __iter__(self):
135         return self._iterate_file(self.__filename)
136
137 class DirectoryParser(CrontabParser):
138
139     def __init__(self, dirname, recursive=False):
140         self.__dirname = dirname
141         self.__recursive = recursive
142         super(DirectoryParser, self).__init__(None)
143
144     def _dirwalker_plain(self):
145         for i in os.listdir(self.__dirname):
146             if os.path.isfile(i):
147                 yield i
148
149     def _dirwalker_recursive(self):
150         for r, d, f in os.walk(self.__dirname):
151             for i in f:
152                 yield i
153
154     def __iter__(self):
155
156         if self.__recursive:
157             dirwalker = self._dirwalker_recursive
158         else:
159             dirwalker = self._dirwalker_plain
160
161         for fname in dirwalker():
162             fullname = os.path.join(self.__dirname, fname)
163             self.__filename = fullname
164             for item in self._iterate_file(fullname):
165                 yield item
166
167 def OptionsParser(args=None, help=u'', **opts):
168
169     from optparse import OptionParser
170     import dbuscron
171     parser = OptionParser(usage=help, version="%prog " + dbuscron.__version__)
172     for opt, desc in opts.iteritems():
173         names = desc.pop('names')
174         desc['dest'] = opt
175         parser.add_option(*names, **desc)
176
177     return parser.parse_args(args)[0]
178