File: main.py

package info (click to toggle)
vmm 0.7.0-0.3
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 1,812 kB
  • sloc: python: 4,710; makefile: 217; sh: 172
file content (68 lines) | stat: -rw-r--r-- 2,343 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# Copyright (c) 2007 - 2021, Pascal Volk
# See COPYING for distribution information.
"""
    VirtualMailManager.cli.main
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~

    VirtualMailManager's command line interface.
"""

from configparser import NoOptionError, NoSectionError

from VirtualMailManager import ENCODING, errors
from VirtualMailManager.config import BadOptionError, ConfigValueError
from VirtualMailManager.cli import w_err
from VirtualMailManager.cli.handler import CliHandler
from VirtualMailManager.constants import EX_MISSING_ARGS, EX_SUCCESS, \
     EX_USER_INTERRUPT, INVALID_ARGUMENT
from VirtualMailManager.cli.subcommands import RunContext, setup_parser


_ = lambda msg: msg


def _get_handler():
    """Try to get a CliHandler. Exit the program when an error occurs."""
    try:
        handler = CliHandler()
    except (errors.NotRootError, errors.PermissionError, errors.VMMError,
            errors.ConfigError) as err:
        w_err(err.code, _('Error: %s') % err.msg)
    else:
        handler.cfg_install()
        return handler


def run(argv):
    parser = setup_parser()
    if len(argv) < 2:
        parser.print_usage()
        parser.exit(status=EX_MISSING_ARGS,
                   message=_('You must specify a subcommand at least.') + '\n')
    args = parser.parse_args()
    handler = _get_handler()
    run_ctx = RunContext(args, handler)
    try:
        args.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, '', _('Ouch!'), '')
    except errors.VMMError as err:
        if handler.has_warnings():
            w_err(0, _('Warnings:'), *handler.get_warnings())
        w_err(err.code, _('Error: %s') % err.msg)
    except (BadOptionError, ConfigValueError) as err:
        w_err(INVALID_ARGUMENT, _('Error: %s') % err)
    except NoSectionError as err:
        w_err(INVALID_ARGUMENT,
              _("Error: Unknown section: '%s'") % err.section)
    except NoOptionError as err:
        w_err(INVALID_ARGUMENT,
              _("Error: No option '%(option)s' in section: '%(section)s'") %
              {'option': err.option, 'section': err.section})
    if handler.has_warnings():
        w_err(0, _('Warnings:'), *handler.get_warnings())
    return EX_SUCCESS

del _