Coverage for cfg_checker/cli/command.py : 52%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1import pkgutil
2import sys
3import traceback
5from cfg_checker.common import config, logger, logger_cli
6from cfg_checker.common.exception import CheckerException
7from cfg_checker.helpers.args_utils import MyParser
9main_pkg_name = __name__.split('.')[0]
10mods_package_name = "modules"
11mods_import_path = main_pkg_name + '.' + mods_package_name
12mods_prefix = mods_import_path + '.'
14commands = {}
15parsers = {}
16helps = {}
17# Pure dynamic magic, loading all 'do_*' methods from available modules
18_m = __import__(mods_import_path, fromlist=[main_pkg_name])
19for _imp, modName, isMod in pkgutil.iter_modules(_m.__path__, mods_prefix):
20 # iterate all packages, add to dict
21 if isMod:
22 # load module
23 _p = _imp.find_module(modName).load_module(modName)
24 # create a shortname
25 mod_name = modName.split('.')[-1]
26 # A package! Create it and add commands
27 commands[mod_name] = \
28 [_n[3:] for _n in dir(_p) if _n.startswith("do_")]
29 parsers[mod_name] = getattr(_p, 'init_parser')
30 helps[mod_name] = getattr(_p, 'command_help')
33def execute_command(args, command):
34 # Validate the commands
35 # check commands
36 if not hasattr(args, 'type') or not args.type:
37 logger_cli.info("\n# Please, type a command listed above")
38 return 0
39 _type = args.type.replace("-", "_") if "-" in args.type else args.type
40 if command not in commands:
41 logger_cli.info("\n# Please, type a command listed above")
42 return 0
43 elif _type not in commands[command]:
44 # check type
45 logger_cli.info(
46 "\n# Please, select '{}' command type listed above".format(
47 command
48 )
49 )
50 return 0
51 else:
52 # form function name to call
53 _method_name = "do_" + _type
54 _target_module = __import__(
55 mods_prefix + command,
56 fromlist=[""]
57 )
58 _method = getattr(_target_module, _method_name)
60 # Execute the command
61 try:
62 _method(args)
63 return 0
64 except CheckerException as e:
65 logger_cli.error("\nERROR: {}".format(
66 e.message
67 ))
69 exc_type, exc_value, exc_traceback = sys.exc_info()
70 logger_cli.debug("\n{}".format(
71 "".join(traceback.format_exception(
72 exc_type,
73 exc_value,
74 exc_traceback
75 ))
76 ))
77 return 1
80def cli_command(_title, _name):
81 my_parser = MyParser(_title)
82 parsers[_name](my_parser)
84 # parse arguments
85 try:
86 args, unknown = my_parser.parse_known_args()
87 except TypeError:
88 logger_cli.info("\n# Please, check arguments")
89 sys.exit(1)
91 if unknown:
92 logger_cli.error(
93 "# Unexpected arguments: {}".format(
94 ", ".join(["'{}'".format(a) for a in unknown])
95 )
96 )
97 sys.exit(1)
99 # force use of sudo
100 config.ssh_uses_sudo = True
102 # Execute the command
103 result = execute_command(args, _name)
104 logger.debug(result)
105 sys.exit(result)