|
| 1 | +import difflib |
| 2 | +import re |
| 3 | +from collections import OrderedDict |
| 4 | + |
| 5 | +import click |
| 6 | +from py42.exceptions import Py42ForbiddenError |
| 7 | +from py42.exceptions import Py42HTTPError |
| 8 | +from py42.exceptions import Py42InvalidRuleOperationError |
| 9 | +from py42.exceptions import Py42LegalHoldNotFoundOrPermissionDeniedError |
| 10 | +from py42.exceptions import Py42UserAlreadyAddedError |
| 11 | + |
| 12 | +from code42cli.errors import Code42CLIError |
| 13 | +from code42cli.errors import LoggedCLIError |
| 14 | +from code42cli.errors import UserDoesNotExistError |
| 15 | +from code42cli.logger import get_main_cli_logger |
| 16 | + |
| 17 | +_DIFFLIB_CUT_OFF = 0.6 |
| 18 | + |
| 19 | + |
| 20 | +class ExceptionHandlingGroup(click.Group): |
| 21 | + """A `click.Group` subclass to add custom exception handling.""" |
| 22 | + |
| 23 | + logger = get_main_cli_logger() |
| 24 | + _original_args = None |
| 25 | + |
| 26 | + def make_context(self, info_name, args, parent=None, **extra): |
| 27 | + |
| 28 | + # grab the original command line arguments for logging purposes |
| 29 | + self._original_args = " ".join(args) |
| 30 | + |
| 31 | + return super().make_context(info_name, args, parent=parent, **extra) |
| 32 | + |
| 33 | + def invoke(self, ctx): |
| 34 | + try: |
| 35 | + return super().invoke(ctx) |
| 36 | + |
| 37 | + except click.UsageError as err: |
| 38 | + self._suggest_cmd(err) |
| 39 | + |
| 40 | + except LoggedCLIError: |
| 41 | + raise |
| 42 | + |
| 43 | + except Code42CLIError as err: |
| 44 | + self.logger.log_error(str(err)) |
| 45 | + raise |
| 46 | + |
| 47 | + except click.ClickException: |
| 48 | + raise |
| 49 | + |
| 50 | + except click.exceptions.Exit: |
| 51 | + raise |
| 52 | + |
| 53 | + except ( |
| 54 | + UserDoesNotExistError, |
| 55 | + Py42UserAlreadyAddedError, |
| 56 | + Py42InvalidRuleOperationError, |
| 57 | + Py42LegalHoldNotFoundOrPermissionDeniedError, |
| 58 | + ) as err: |
| 59 | + self.logger.log_error(err) |
| 60 | + raise Code42CLIError(str(err)) |
| 61 | + |
| 62 | + except Py42ForbiddenError as err: |
| 63 | + self.logger.log_verbose_error(self._original_args, err.response.request) |
| 64 | + raise LoggedCLIError( |
| 65 | + "You do not have the necessary permissions to perform this task. " |
| 66 | + "Try using or creating a different profile." |
| 67 | + ) |
| 68 | + |
| 69 | + except Py42HTTPError as err: |
| 70 | + self.logger.log_verbose_error(self._original_args, err.response.request) |
| 71 | + raise LoggedCLIError("Problem making request to server.") |
| 72 | + |
| 73 | + except OSError: |
| 74 | + raise |
| 75 | + |
| 76 | + except Exception: |
| 77 | + self.logger.log_verbose_error() |
| 78 | + raise LoggedCLIError("Unknown problem occurred.") |
| 79 | + |
| 80 | + @staticmethod |
| 81 | + def _suggest_cmd(usage_err): |
| 82 | + """Handles fuzzy suggestion of commands that are close to the bad command entered.""" |
| 83 | + if usage_err.message is not None: |
| 84 | + match = re.match("No such command '(.*)'.", usage_err.message) |
| 85 | + if match: |
| 86 | + bad_arg = match.groups()[0] |
| 87 | + available_commands = list(usage_err.ctx.command.commands.keys()) |
| 88 | + suggested_commands = difflib.get_close_matches( |
| 89 | + bad_arg, available_commands, cutoff=_DIFFLIB_CUT_OFF |
| 90 | + ) |
| 91 | + if not suggested_commands: |
| 92 | + raise usage_err |
| 93 | + usage_err.message = "No such command '{}'. Did you mean {}?".format( |
| 94 | + bad_arg, " or ".join(suggested_commands) |
| 95 | + ) |
| 96 | + raise usage_err |
| 97 | + |
| 98 | + |
| 99 | +class OrderedGroup(click.Group): |
| 100 | + """A `click.Group` subclass that uses an `OrderedDict` to store commands so the help text lists |
| 101 | + them in the order they were defined/added to the group. |
| 102 | + """ |
| 103 | + |
| 104 | + def __init__(self, name=None, commands=None, **attrs): |
| 105 | + super().__init__(name, commands, **attrs) |
| 106 | + # the registered subcommands by their exported names. |
| 107 | + self.commands = commands or OrderedDict() |
| 108 | + |
| 109 | + def list_commands(self, ctx): |
| 110 | + return self.commands |
0 commit comments