VirtualMailManager/cli/main.py
branchv0.6.x
changeset 340 4515afec62e5
parent 232 3c766114d0b9
child 343 9232ed7e4d85
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/VirtualMailManager/cli/main.py	Thu Aug 05 05:08:02 2010 +0000
@@ -0,0 +1,66 @@
+# -*- coding: UTF-8 -*-
+# Copyright 2007 - 2010, Pascal Volk
+# See COPYING for distribution information.
+"""
+    VirtualMailManager.cli.main
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+    VirtualMailManager's command line interface.
+"""
+
+from VirtualMailManager import ENCODING, errors
+from VirtualMailManager.config import ConfigValueError
+from VirtualMailManager.cli import w_err
+from VirtualMailManager.cli.handler import CliHandler
+from VirtualMailManager.constants import DATABASE_ERROR, EX_MISSING_ARGS, \
+     EX_SUCCESS, EX_UNKNOWN_COMMAND, EX_USER_INTERRUPT
+from VirtualMailManager.cli.subcommands import RunContext, cmd_map, usage
+
+
+_ = lambda msg: msg
+
+def _get_handler():
+    """Try to get a CliHandler. Exit the program when an error occurs."""
+    try:
+        handler = CliHandler()
+        handler.cfg_install()
+    except (errors.NotRootError, errors.PermissionError, errors.VMMError,
+            errors.ConfigError, ConfigValueError), err:
+        w_err(err.code, _(u'Error: %s') % err.msg)
+    else:
+        return handler
+
+
+def run(argv):
+    if len(argv) < 2:
+        usage(EX_MISSING_ARGS, _(u"You must specify a subcommand at least"))
+
+    sub_cmd = argv[1].lower()
+    if sub_cmd in cmd_map:
+        cmd_func = cmd_map[sub_cmd].func
+    else:
+        for cmd in cmd_map.itervalues():
+            if cmd.alias == sub_cmd:
+                cmd_func = cmd.func
+                sub_cmd = cmd.name
+                break
+        else:
+            usage(EX_UNKNOWN_COMMAND, _(u"Unknown subcommand: '%s'") % sub_cmd)
+
+    handler = _get_handler()
+    run_ctx = RunContext(argv, handler, sub_cmd)
+    try:
+        cmd_func(run_ctx)
+    except (EOFError, KeyboardInterrupt):
+        # TP: We have to cry, because root has killed/interrupted vmm
+        # with Ctrl+C or Ctrl+D.
+        w_err(EX_USER_INTERRUPT, '', _(u'Ouch!'), '')
+    except errors.VMMError, err:
+        if err.code != DATABASE_ERROR:
+            w_err(err.code, _(u'Error: %s') % err.msg)
+        w_err(err.code, unicode(err.msg, ENCODING, 'replace'))
+    if handler.has_warnings():
+        w_err(0, _(u'Warnings:'), *handler.get_warnings())
+    return EX_SUCCESS
+
+del _