6dcd6cbd2676a09c04ea71fe547e54e2d6996969
[dbuscron] / dbuscron / parser.py
1 from __future__ import with_statement
2 import re
3 from dbuscron.bus import DbusBus
4
5 try:
6     from itertools import product
7 except ImportError:
8     def product(*args):
9         if args:
10             head, tail = args[0], args[1:]
11             for h in head:
12                 for t in product(*tail):
13                     yield (h,) + t
14     
15         else:
16             yield ()
17
18 class CrontabParser(object):
19     __fields_sep = re.compile(r'\s+')
20     __envvar_sep = re.compile(r'\s*=\s*')
21     __fields = [
22             'bus_',
23             'type_',
24             'sender_',
25             'interface_',
26             'path_',
27             'member_',
28             'destination_',
29             'args_',
30             #'command'
31             ]
32
33     def __init__(self, fname):
34         self.__bus = DbusBus()
35         self.__filename = fname
36         self.__environ = dict()
37
38     @property
39     def environ(self):
40         return self.__environ
41
42     def __iter__(self):
43         # bus type sender interface path member destination args command
44         with open(self.__filename) as f:
45             for line in f:
46                 line = line.strip()
47
48                 if not line or line.startswith('#'):
49                     continue
50
51                 parts = self.__fields_sep.split(line, 8)
52                 if len(parts) < 9:
53                     parts = self.__envvar_sep(line, 1)
54                     if len(parts) == 2:
55                         self.__environ[parts[0]] = parts[1]
56                     continue
57
58                 rule = [(None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,)]
59
60                 for p in range(1, 8):
61                     if parts[p] != '*':
62                         rule[p] = parts[p].split(',')
63
64                 command = parts[8]
65
66                 if parts[0] == '*' or parts[0] == 'S,s' or parts[0] == 's,S':
67                     rule[0] = (self.__bus.system, self.__bus.session)
68                 elif parts[0] == 's':
69                     rule[0] = (self.__bus.session,)
70                 elif parts[0] == 'S':
71                     rule[0] = (self.__bus.system,)
72                     
73                 for r in product(*rule):
74                     if r[7]:
75                         r[7] = r[7].split(';')
76                     ruled = dict()
77                     for i, f in enumerate(self.__fields):
78                         ruled[f] = r[i]
79                     yield ruled, command
80