Alex | 265f45e | 2019-04-23 18:51:23 -0500 | [diff] [blame^] | 1 | import sys |
| 2 | import traceback |
| 3 | |
| 4 | from cfg_checker.common import logger_cli |
| 5 | from cfg_checker.common.exception import CheckerException |
| 6 | |
| 7 | # TODO: auto-create types for each command |
| 8 | package_command_types = ['report'] |
| 9 | network_command_types = ['check', 'report'] |
| 10 | reclass_command_types = ['list', 'diff'] |
| 11 | |
| 12 | commands = { |
| 13 | 'packages': package_command_types, |
| 14 | 'network': network_command_types, |
| 15 | 'reclass': reclass_command_types |
| 16 | } |
| 17 | |
| 18 | |
| 19 | def execute_command(args, command): |
| 20 | # Validate the commands |
| 21 | # check command |
| 22 | if command not in commands: |
| 23 | logger_cli.info("\n# Please, type a command listed above") |
| 24 | return 0 |
| 25 | elif args.type not in commands[command]: |
| 26 | # check type |
| 27 | logger_cli.info( |
| 28 | "\n# Please, select '{}' command type listed above".format( |
| 29 | command |
| 30 | ) |
| 31 | ) |
| 32 | return 0 |
| 33 | else: |
| 34 | # form function name to call |
| 35 | _method_name = "do_" + args.type |
| 36 | _target_module = __import__( |
| 37 | "cfg_checker.modules."+command, |
| 38 | fromlist=[""] |
| 39 | ) |
| 40 | _method = getattr(_target_module, _method_name) |
| 41 | |
| 42 | # Execute the command |
| 43 | try: |
| 44 | _method(args) |
| 45 | return 0 |
| 46 | except CheckerException as e: |
| 47 | logger_cli.error("\nERROR: {}".format( |
| 48 | e.message |
| 49 | )) |
| 50 | |
| 51 | exc_type, exc_value, exc_traceback = sys.exc_info() |
| 52 | logger_cli.debug("\n{}".format( |
| 53 | "".join(traceback.format_exception( |
| 54 | exc_type, |
| 55 | exc_value, |
| 56 | exc_traceback |
| 57 | )) |
| 58 | )) |
| 59 | return 1 |