moved shell part into modules
authorKonstantin Stepanov <kstep@p-nut.info>
Fri, 17 Dec 2010 12:49:18 +0000 (14:49 +0200)
committerKonstantin Stepanov <kstep@p-nut.info>
Fri, 17 Dec 2010 12:49:18 +0000 (14:49 +0200)
dbuscron.py
dbuscron/shell/__init__.py [new file with mode: 0644]
dbuscron/shell/edit.py [new file with mode: 0644]
dbuscron/shell/main.py [new file with mode: 0644]
dbuscrontab.py

index 4588f61..a5391e8 100755 (executable)
@@ -5,72 +5,14 @@
 # Examples for N900:
 #
 # Headphones unplugged:
-# S signal * org.freedesktop.Hal.Manager /org/freedesktop/Hal/Manager DeviceRemoved * * echo Headphones unplugged;
+# S signal * org.freedesktop.Hal.Device /org/freedesktop/Hal/devices/platform_headphone Condition * ButtonPressed;connection echo Headphones state changed: $(cat /sys/devices/platform/gpio-switch/headphone/state)
 #
 # Call recieved:
 # S signal * com.nokia.csd.Call /com/nokia/csd/call Coming * * echo $DBUS_ARG1 is calling
 #
 
-import sys
-
-if __name__ == '__main__':
-
-    from dbuscron import Logger, OptionsParser
-
-    options = OptionsParser(
-            daemon=dict(names=('-f', '--nodaemon'), action='store_false', default=True),
-            quiet=dict(names=('--quiet', '-q'), action='count', default=0),
-            verbose=dict(names=('--verbose', '-v'), action='count', default=0),
-            config=dict(names=('--conf', '--config', '-c'), default='/etc/dbuscrontab'),
-            logfile=dict(names=('--log', '--logfile', '-l')))
-
-    logout = sys.stderr
-    if options.logfile:
-        logout = open(options.logfile, 'wb')
-
-    log = Logger(__name__, out=logout)
-    log.level = options.verbose - options.quiet + Logger.WARNING
-
-    if options.daemon:
-        from dbuscron.daemonize import daemonize
-        daemonize(
-            pidfile='/var/run/dbuscron.pid',
-            logfile='/var/log/dbuscron.log'
-            )
-
-    from dbuscron import DbusBus, DbusRule, Command, Commands, CrontabParser
-
-    bus = DbusBus()
-    commands = Commands()
-
-    crontab = CrontabParser(options.config)
-
-    def load_config(parser):
-        for rule, cmd in parser:
-            matcher = DbusRule(**rule)
-            command = Command(cmd)
-            matcher.register()
-            log('rule parsed', matcher, command)
-            commands.add(matcher, command)
-
-    load_config(crontab)
-
-    def reload_config_on_signal(sig_no, stack):
-        log('Signal #%d received: reloading config...' % (sig_no))
-        commands.clear()
-        load_config(crontab)
-        log('Done config reloading.')
-
-    import signal
-    signal.signal(signal.SIGHUP, reload_config_on_signal)
-
-    commands.environ = crontab.environ
-    bus.attach_handler(commands.handler)
-
-    try:
-        bus.listen()
-    except KeyboardInterrupt:
-        sys.exit(2)
+from dbuscron.shell import main
+main.run()
 
 # vim: ts=8 sts=4 sw=4 et
 
diff --git a/dbuscron/shell/__init__.py b/dbuscron/shell/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/dbuscron/shell/edit.py b/dbuscron/shell/edit.py
new file mode 100644 (file)
index 0000000..810b7dc
--- /dev/null
@@ -0,0 +1,104 @@
+
+import os, sys, shutil, signal, tempfile, pipes
+conffile = '/etc/dbuscrontab'
+pidfile = '/var/run/dbuscron.pid'
+
+from dbuscron.parser import CrontabParser, CrontabParserError
+
+def create_temp_file(orig_file):
+    try:
+        temp_file = tempfile.mktemp(prefix=os.path.basename(orig_file))
+        shutil.copy(orig_file, temp_file)
+        return temp_file
+    except:
+        raise SystemError('Unable to make copy of dbuscrontab file.')
+
+def run_system_editor(filename):
+    editor = pipes.quote(os.environ.get('EDITOR', '/usr/bin/vim'))
+    if os.system(editor + ' ' + pipes.quote(filename)) != 0:
+        raise SystemError('Editor returned non-zero status value.')
+
+def get_dbuscron_pid():
+    try:
+        f = os.popen('initctl status dbuscron', 'r')
+        status = f.readline()
+        f.close()
+        return int(status.strip().split(' ').pop())
+    except:
+        raise SystemError('Unable to get PID of dbuscron job.')
+
+def check_syntax(filename):
+    parser = CrontabParser(filename)
+    try:
+        for rule, command in parser:
+            pass
+    except CrontabParserError, e:
+        print e.message
+        raise SystemError("File %s has syntax errors." % (filename))
+
+def run():
+
+    try:
+        action = sys.argv[1]
+    except IndexError:
+        action = None
+
+    try:
+        if action == '-e':
+
+            # 1. create temporary config file copy
+            temp_file = create_temp_file(conffile)
+            mod_time = os.path.getmtime(temp_file)
+
+            try:
+                # 2. run system editor on this file
+                run_system_editor(temp_file)
+
+                # 3. check if this file is changed
+                if os.path.getmtime(temp_file) <= mod_time:
+                    print 'File was not changed.'
+                    sys.exit(2)
+
+                # 4. check this file's syntax
+                check_syntax(temp_file)
+
+                # 5. replace system wide config file with new one
+                shutil.move(temp_file, conffile)
+
+            finally:
+                try:
+                    os.unlink(temp_file)
+                except OSError:
+                    pass
+
+            # 6. send sighup to dbuscron daemon
+            pid = get_dbuscron_pid()
+            os.kill(pid, signal.SIGHUP)
+
+            print "Everything's OK, SIGHUP to dbuscron is sent."
+
+        elif action == '-l':
+            f = open(conffile, 'r')
+            for l in f:
+                print l.strip()
+            f.close()
+
+        elif action == '-k':
+            check_syntax(conffile)
+            print "File %s has no syntax errors." % (conffile)
+
+        else:
+            print """
+Usage:
+    %(myname)s { -e | -l }
+
+    -e      edit %(conffile)s file
+    -l      list contents of %(conffile)s file
+    -k      check %(conffile)s's syntax
+
+""" % dict(myname=os.path.basename(sys.argv[0]), conffile=conffile)
+
+    except SystemError, e:
+        print e.message
+        sys.exit(1)
+
diff --git a/dbuscron/shell/main.py b/dbuscron/shell/main.py
new file mode 100644 (file)
index 0000000..fbbb549
--- /dev/null
@@ -0,0 +1,60 @@
+import sys
+from dbuscron import Logger, OptionsParser
+
+def run():
+
+    options = OptionsParser(
+            daemon=dict(names=('-f', '--nodaemon'), action='store_false', default=True),
+            quiet=dict(names=('--quiet', '-q'), action='count', default=0),
+            verbose=dict(names=('--verbose', '-v'), action='count', default=0),
+            config=dict(names=('--conf', '--config', '-c'), default='/etc/dbuscrontab'),
+            logfile=dict(names=('--log', '--logfile', '-l')))
+
+    logout = sys.stderr
+    if options.logfile:
+        logout = open(options.logfile, 'wb')
+
+    log = Logger(__name__, out=logout)
+    log.level = options.verbose - options.quiet + Logger.WARNING
+
+    if options.daemon:
+        from dbuscron.daemonize import daemonize
+        daemonize(
+            pidfile='/var/run/dbuscron.pid',
+            logfile='/var/log/dbuscron.log'
+            )
+
+    from dbuscron import DbusBus, DbusRule, Command, Commands, CrontabParser
+
+    bus = DbusBus()
+    commands = Commands()
+
+    crontab = CrontabParser(options.config)
+
+    def load_config(parser):
+        for rule, cmd in parser:
+            matcher = DbusRule(**rule)
+            command = Command(cmd)
+            matcher.register()
+            log('rule parsed', matcher, command)
+            commands.add(matcher, command)
+
+    load_config(crontab)
+
+    def reload_config_on_signal(sig_no, stack):
+        log('Signal #%d received: reloading config...' % (sig_no))
+        commands.clear()
+        load_config(crontab)
+        log('Done config reloading.')
+
+    import signal
+    signal.signal(signal.SIGHUP, reload_config_on_signal)
+
+    commands.environ = crontab.environ
+    bus.attach_handler(commands.handler)
+
+    try:
+        bus.listen()
+    except KeyboardInterrupt:
+        sys.exit(2)
+
index 4f61a3f..2a42912 100755 (executable)
@@ -1,105 +1,5 @@
 #!/usr/bin/python
 
-import os, sys, shutil, signal, tempfile, pipes
-conffile = '/etc/dbuscrontab'
-pidfile = '/var/run/dbuscron.pid'
-
-from dbuscron.parser import CrontabParser, CrontabParserError
-
-def create_temp_file(orig_file):
-    try:
-        temp_file = tempfile.mktemp(prefix=os.path.basename(orig_file))
-        shutil.copy(orig_file, temp_file)
-        return temp_file
-    except:
-        raise SystemError('Unable to make copy of dbuscrontab file.')
-
-def run_system_editor(filename):
-    editor = pipes.quote(os.environ.get('EDITOR', '/usr/bin/vim'))
-    if os.system(editor + ' ' + pipes.quote(filename)) != 0:
-        raise SystemError('Editor returned non-zero status value.')
-
-def get_dbuscron_pid():
-    try:
-        f = os.popen('initctl status dbuscron', 'r')
-        status = f.readline()
-        f.close()
-        return int(status.strip().split(' ').pop())
-    except:
-        raise SystemError('Unable to get PID of dbuscron job.')
-
-def check_syntax(filename):
-    parser = CrontabParser(filename)
-    try:
-        for rule, command in parser:
-            pass
-    except CrontabParserError, e:
-        print e.message
-        raise SystemError("File %s has syntax errors." % (filename))
-
-if __name__ == '__main__':
-
-    try:
-        action = sys.argv[1]
-    except IndexError:
-        action = None
-
-    try:
-        if action == '-e':
-
-            # 1. create temporary config file copy
-            temp_file = create_temp_file(conffile)
-            mod_time = os.path.getmtime(temp_file)
-
-            try:
-                # 2. run system editor on this file
-                run_system_editor(temp_file)
-
-                # 3. check if this file is changed
-                if os.path.getmtime(temp_file) <= mod_time:
-                    print 'File was not changed.'
-                    sys.exit(2)
-
-                # 4. check this file's syntax
-                check_syntax(temp_file)
-
-                # 5. replace system wide config file with new one
-                shutil.move(temp_file, conffile)
-
-            finally:
-                try:
-                    os.unlink(temp_file)
-                except OSError:
-                    pass
-
-            # 6. send sighup to dbuscron daemon
-            pid = get_dbuscron_pid()
-            os.kill(pid, signal.SIGHUP)
-
-            print "Everything's OK, SIGHUP to dbuscron is sent."
-
-        elif action == '-l':
-            f = open(conffile, 'r')
-            for l in f:
-                print l.strip()
-            f.close()
-
-        elif action == '-k':
-            check_syntax(conffile)
-            print "File %s has no syntax errors." % (conffile)
-
-        else:
-            print """
-Usage:
-    %(myname)s { -e | -l }
-
-    -e      edit %(conffile)s file
-    -l      list contents of %(conffile)s file
-    -k      check %(conffile)s's syntax
-
-""" % dict(myname=os.path.basename(sys.argv[0]), conffile=conffile)
-
-    except SystemError, e:
-        print e.message
-        sys.exit(1)
+from dbuscron.shell import edit
+edit.run()