|
1 # -*- coding: UTF-8 -*- |
|
2 # Copyright 2007 - 2010, Pascal Volk |
|
3 # See COPYING for distribution information. |
|
4 """ |
|
5 VirtualMailManager.cli.main |
|
6 ~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
7 |
|
8 VirtualMailManager's command line interface. |
|
9 """ |
|
10 |
|
11 from VirtualMailManager import ENCODING, errors |
|
12 from VirtualMailManager.config import ConfigValueError |
|
13 from VirtualMailManager.cli import w_err |
|
14 from VirtualMailManager.cli.handler import CliHandler |
|
15 from VirtualMailManager.constants import DATABASE_ERROR, EX_MISSING_ARGS, \ |
|
16 EX_SUCCESS, EX_UNKNOWN_COMMAND, EX_USER_INTERRUPT |
|
17 from VirtualMailManager.cli.subcommands import RunContext, cmd_map, usage |
|
18 |
|
19 |
|
20 _ = lambda msg: msg |
|
21 |
|
22 def _get_handler(): |
|
23 """Try to get a CliHandler. Exit the program when an error occurs.""" |
|
24 try: |
|
25 handler = CliHandler() |
|
26 handler.cfg_install() |
|
27 except (errors.NotRootError, errors.PermissionError, errors.VMMError, |
|
28 errors.ConfigError, ConfigValueError), err: |
|
29 w_err(err.code, _(u'Error: %s') % err.msg) |
|
30 else: |
|
31 return handler |
|
32 |
|
33 |
|
34 def run(argv): |
|
35 if len(argv) < 2: |
|
36 usage(EX_MISSING_ARGS, _(u"You must specify a subcommand at least")) |
|
37 |
|
38 sub_cmd = argv[1].lower() |
|
39 if sub_cmd in cmd_map: |
|
40 cmd_func = cmd_map[sub_cmd].func |
|
41 else: |
|
42 for cmd in cmd_map.itervalues(): |
|
43 if cmd.alias == sub_cmd: |
|
44 cmd_func = cmd.func |
|
45 sub_cmd = cmd.name |
|
46 break |
|
47 else: |
|
48 usage(EX_UNKNOWN_COMMAND, _(u"Unknown subcommand: '%s'") % sub_cmd) |
|
49 |
|
50 handler = _get_handler() |
|
51 run_ctx = RunContext(argv, handler, sub_cmd) |
|
52 try: |
|
53 cmd_func(run_ctx) |
|
54 except (EOFError, KeyboardInterrupt): |
|
55 # TP: We have to cry, because root has killed/interrupted vmm |
|
56 # with Ctrl+C or Ctrl+D. |
|
57 w_err(EX_USER_INTERRUPT, '', _(u'Ouch!'), '') |
|
58 except errors.VMMError, err: |
|
59 if err.code != DATABASE_ERROR: |
|
60 w_err(err.code, _(u'Error: %s') % err.msg) |
|
61 w_err(err.code, unicode(err.msg, ENCODING, 'replace')) |
|
62 if handler.has_warnings(): |
|
63 w_err(0, _(u'Warnings:'), *handler.get_warnings()) |
|
64 return EX_SUCCESS |
|
65 |
|
66 del _ |