--sessionaddr option to set custom session bus address
[dbuscron] / dbuscron / parser.py
index f025709..7ddc75a 100644 (file)
@@ -1,23 +1,43 @@
+# encoding: utf-8
 from __future__ import with_statement
 import re
 from dbuscron.bus import DbusBus
 
-try:
-    from itertools import product
-except ImportError:
-    def product(*args):
-        if args:
-            head, tail = args[0], args[1:]
-            for h in head:
-                for t in product(*tail):
-                    yield (h,) + t
-    
+def product(*args):
+    if args:
+        head, tail = args[0], args[1:]
+        for h in head:
+            for t in product(*tail):
+                yield (h,) + t
+
+    else:
+        yield ()
+
+class CrontabParserError(SyntaxError):
+    def __init__(self, message, lineno, expected=None):
+        if expected:
+            if isinstance(expected, (tuple, list)):
+                exp = ' (expected %s or %s)' % (', '.join(expected[:-1]), expected[-1])
         else:
-            yield ()
+            exp = ''
+
+        msg = '%s%s at line %d' % (message, exp, lineno)
+
+        SyntaxError.__init__(self, msg)
 
 class CrontabParser(object):
     __fields_sep = re.compile(r'\s+')
     __envvar_sep = re.compile(r'\s*=\s*')
+    __fields_chk = {
+            'bus_'         : None,
+            'type_'        : ('signal','method_call','method_return','error'),
+            'sender_'      : None,
+            'interface_'   : re.compile(r'^[a-zA-Z][a-zA-Z0-9_.]+$'),
+            'path_'        : re.compile(r'^/[a-zA-Z0-9_/]+$'),
+            'member_'      : re.compile(r'^[a-zA-Z][a-zA-Z0-9_]+$'),
+            'destination_' : None,
+            'args_'        : None,
+            }
     __fields = [
             'bus_',
             'type_',
@@ -27,7 +47,6 @@ class CrontabParser(object):
             'member_',
             'destination_',
             'args_',
-            #'command'
             ]
 
     def __init__(self, fname):
@@ -41,8 +60,10 @@ class CrontabParser(object):
 
     def __iter__(self):
         # bus type sender interface path member destination args command
+        lineno = 0
         with open(self.__filename) as f:
             for line in f:
+                lineno += 1
                 line = line.strip()
 
                 if not line or line.startswith('#'):
@@ -53,9 +74,11 @@ class CrontabParser(object):
                     parts = self.__envvar_sep(line, 1)
                     if len(parts) == 2:
                         self.__environ[parts[0]] = parts[1]
-                    continue
+                        continue
+
+                    raise CrontabParserError('Unexpected number of records', lineno)
 
-                rule = [('s','S'), ('signal','method_call','method_return','error'), (None,), (None,), (None,), (None,), (None,), (None,)]
+                rule = [('s','S'), self.__fields_chk['type_'], (None,), (None,), (None,), (None,), (None,), (None,)]
 
                 for p in range(0, 8):
                     if parts[p] != '*':
@@ -70,13 +93,34 @@ class CrontabParser(object):
                     elif r[0] == 's':
                         r[0] = self.__bus.session
                     else:
-                        continue
-       
+                        raise CrontabParserError('Unexpected bus value', lineno, expected=('S', 's', '*'))
+
                     if r[7]:
                         r[7] = r[7].split(';')
 
                     ruled = dict()
                     for i, f in enumerate(self.__fields):
+                        if self.__fields_chk[f]:
+                            if isinstance(self.__fields_chk[f], tuple):
+                                if r[i] not in self.__fields_chk[f]:
+                                    raise CrontabParserError('Unexpected %s value' % (f.strip('_')), lineno,
+                                            expected=self.__fields_chk[f])
+                            else:
+                                if not self.__fields_chk[f].match(r[i]):
+                                    raise CrontabParserError('Incorrect %s value' % (f.strip('_')), lineno)
                         ruled[f] = r[i]
+
                     yield ruled, command
 
+def OptionsParser(args=None, help=u'', **opts):
+
+    from optparse import OptionParser
+    import dbuscron
+    parser = OptionParser(usage=help, version="%prog "+dbuscron.__version__)
+    for opt, desc in opts.iteritems():
+        names = desc.pop('names')
+        desc['dest'] = opt
+        parser.add_option(*names, **desc)
+
+    return parser.parse_args(args)[0]
+